Walking an XML tree in C#

后端 未结 4 970
挽巷
挽巷 2021-02-19 22:35

I\'m new to .net and c#, so I want to make sure i\'m using the right tool for the job.

The XML i\'m receiving is a description of a directory tree on another machine, so

4条回答
  •  旧时难觅i
    2021-02-19 23:18

    I would use the XLINQ classes in System.Xml.Linq (this is the namespace and the assembly you will need to reference). Load the XML into and XDocument:

    XDocument doc = XDocument.Parse(someString);
    

    Next you can either use recursion or a pseudo-recursion loop to iterate over the child nodes. You can choose you child nodes like:

    //if Directory is tag name of Directory XML
    //Note: Root is just the root XElement of the document
    var directoryElements = doc.Root.Elements("Directory"); 
    
    //you get the idea
    var fileElements = doc.Root.Elements("File"); 
    

    The variables directoryElements and fileElements will be IEnumerable types, which means you can use something like a foreach to loop through all of the elements. One way to build up you elements would be something like this:

    List files = new List();
    
    foreach(XElelement fileElement in fileElements)
    {
      files.Add(new MyFileType()
        {     
          Prop1 = fileElement.Element("Prop1"), //assumes properties are elements
          Prop2 = fileElement.Element("Prop2"),
        });
    }
    

    In the example, MyFileType is a type you created to represent files. This is a bit of a brute-force attack, but it will get the job done.

    If you want to use XPath you will need to using System.Xml.XPath.


    A Note on System.Xml vs System.Xml.Linq

    There are a number of XML classes that have been in .Net since the 1.0 days. These live (mostly) in System.Xml. In .Net 3.5, a wonderful, new set of XML classes were released under System.Xml.Linq. I cannot over-emphasize how much nicer they are to work with than the old classes in System.Xml. I would highly recommend them to any .Net programmer and especially someone just getting into .Net/C#.

提交回复
热议问题