Read child elements using C# from xml

依然范特西╮ 提交于 2019-11-30 09:26:34

问题


Greeting, What is the best practice to read all attributes from a child elements by ID attributes using C# in xml file listed down.

Thank you,

 <?xml version="1.0" encoding="utf-8"?>
 <WinDLN>

  <Program ID="1" Name="CIS562" StartDate="9/8/2010 5:50:00 PM" EndDate="9/8/2010 9:15:00 PM" />

  <Program ID="2" Name="CIS532" StartDate="10/8/2010 5:50:00 PM" EndDate="10/8/2010 9:15:00 PM" />

  <Program ID="3" Name="ECE552" StartDate="6/8/2010 5:50:00 PM" EndDate="6/8/2010 9:15:00 PM" />

</WinDLN>

回答1:


The following LINQ call should do the trick:

var attrs = 
  doc.Descendants("Program").First(prog =>
    prog.Attribute("ID").Value == "2").Attributes();

The Descendants method gives you all elements (anywhere) in the XML document that are named "Program". Using First, you can get the first one that matches some specified predicate (e.g. has "ID" equal to "2"). Note that you can use FirstOrDefault if you want to get null when there is no such element. Finally, Attributes gives you a collection of all attribtues of the element.

I think that using LINQ to XML if you can is preferrable - you'll write the same code when working with XML or other data sources, so reading and writing the code is easy (once you learn LINQ).




回答2:


There are many ways to do it, e.g. LINQ over XML. But using Xpath is definitely not dead yet:

class Program
{
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        string xml = @"... your xml ";
        doc.LoadXml(xml);
        // Using SelectNodes with Xpath
        XmlNodeList list = doc.SelectNodes("WinDLN/Program[@ID='2']");
        Console.WriteLine(list.Count); // prints 1
        list = doc.SelectNodes("WinDLN/Program[@ID]");
        Console.WriteLine(list.Count); // prints 3 (selected all IDs)
    }
}

What method you'll choose is most often a matter of taste, select the API you're most comfortable with.



来源:https://stackoverflow.com/questions/4006916/read-child-elements-using-c-sharp-from-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!