读取XML文件以获取所有子节点

时间:2014-09-18 09:22:59

标签: c# xml get nodes put

我有一个类似于下面的XML文件。目前,如果我想更改值,我必须进入XML并根据需要更改/添加/删除记录。

<configuration>
    <locations>
        <add key="1234" type="Type1" location="Default Location 1" value="10"/>
        <add key="4567" type="Type2" location="Default Location 1" value="13"/>
        <add key="7890" type="Type1" location="Default Location 2" value="17"/>
    </locations>
</configuration>

我为此编写了一个Windows窗体GUI以及该软件使用的其他一些XML。我可以在其他XML中获取/ putsettings,因为它们有节点名称,但是这个文件(最初创建时)是以不同的方式制作的。

我需要将每一行作为字符串,以便我可以将其拆分并在屏幕上显示我需要的内容(键/类型/位置/值)。然后我需要在更新时用更新信息更新文件。

我正在寻求帮助:

  • 检索<locations>

  • 中的所有节点属性
  • 清除<locations>中的所有节点,然后添加带有属性的节点,以便考虑所有可能性(删除/添加/更新记录)等

3 个答案:

答案 0 :(得分:0)

您可以使用XmlReader为您完成工作。

像这样;

        XmlReader reader = new XmlReader(filepath)

        string s = "";

        while(reader.Read())
        {
              if(reader.HasAttributes)
              {
               s  = reader["attributename"].Value;
              }
         }

我承诺不会编译,因为我是通过手机输入的。

此后,您可以使用存储的值并使用XmlWriter将数据写入文件。

我还想指出,如果你正在处理大量数据,XmlReader可能是要走的路。使用XmlDocument会将整个文档加载到RAM中,这可能会导致性能问题。 XmlReader将使用比XmlDocument更少的内存流式传输数据。

答案 1 :(得分:0)

我建议您只使用命名空间XmlSerializer中的System.Xml.Serialization类。您可以使用属性microsoft define。 然后,您可以轻松地将XML序列化和反序列化到您的结构或类中。

答案 2 :(得分:0)

System.Xml.Linq命名空间查看XDocument。与较旧的XmlDocument类相比,它是用于处理XML文档的较新API。与XmlDocumentXmlReader相比,它在常见情况下非常容易使用。用法示例:

XDocument doc = XDocument.Load("path_to_xml_file.xml");
List<XElement> adds = doc.Descendants("locations").Elements("add");
foreach(XElement add in adds)
{
    //get attribute of current <add> node, for example key & type attribute :
    var key = (int)add.Attribute("key");
    var type = (string)add.Attribute("type");
    .....
}