简体   繁体   中英

Reading XML File to get all Child Nodes

I have an XML file which is similar to below. At the moment if I want to change values I have to go into the XML and change/add/remove records as required.

<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>

I'm writing a Windows Form GUI for this and a few other XMLs which the software uses. I can get/putsettings in the other XMLs as they have node names, but this file, (when originally created) was made differently.

I need to get each row as a string so I can then split it and display what I need on the screen (key/type/location/value). I then need to update the file with the information when updated.

I'm looking for some help in:

  • retrieving all node attributes within <locations>

  • clearing out all nodes within <locations> and then adding the nodes with attributes back into so that all eventualities are considered (records removed/added/updated) etc

You could use an XmlReader to do the work for you.

Something like this;

        XmlReader reader = new XmlReader(filepath)

        string s = "";

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

Can't promise it will compile since I typed it from my phone.

Thereafter, you can use the stored values and use the XmlWriter to write the data to a file.

I'd also like to point out that if you are working with lots of data, XmlReader is probably the way to go. Using XmlDocument will load the entire document in the RAM, which could lead to performance issues. XmlReader will stream the data, using way less memory than XmlDocument will ever do.

I suggest you just use the XmlSerializer class in namespace System.Xml.Serialization . You can use attribute microsoft define. Then you can serialize and deserialize the XML to your structure or class easily.

Look into XDocument from System.Xml.Linq namespace. It is a newer API for dealing with XML document compared to the older XmlDocument class. And it is very easy to use in common scenario compared to XmlDocument or XmlReader . Usage example :

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");
    .....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM