C# 读取 XML 元素和文本

C# Read XML Element and Text

我仍然在掌握 C#,并且我一直在寻找多年的时间来尝试找到解决我的问题的方法。 (这是一个帮助我学习C#的实践项目)[​​=14=]

我可以创建并写入 XML 设置文件,但我很难从中获取数据。

我尝试使用 here 的最佳答案,但没有成功。

我想从 XML 文件中获取元素和内部文本并放入一个 2 列列表中(我目前正在使用字典,如果我 have/need 到)

在第一列中,我想要元素名称,在第二列中,我想要内部文本。

然后我只想写出我创建的列表

XML

<settings>
    <view1>enabled</view1>
    <view2>disabled</view2>
</settings>

C#

private Dictionary<string, string> settingsList = new Dictionary<string, string>();

private void CreateSettings()
{
    XDocument xmlSettings = new XDocument(
        new XElement(
            "settings",
            new XElement("view1", "enabled"),
            new XElement("view2", "disabled")))

    xmlSettings.Save(FilePath);
}

private void ReadSettings
{
    XDocument xmlSettings = XDocument.Load(FilePath);

    //READ XML FROM FILE PATH AND ADD TO LIST
}

您可以使用ToDictionary方法将您的设置放入字典:

settingsList = xmlSettings.Descendants().ToDictionary(x => x.Name, x => x.Value);

假设您有 class

public class Setting
{
    public String Name { get; set; }
    public String Value { get; set; }
}

然后您必须对 return class Setting

的实例列表执行以下操作
var settings = from node in xmlSettings.Descendants("settings").Descendants()
               select new Setting { Name = node.Name.LocalName, Value = node.Value };