Reading children using c # from xml

Greetings, What is the best practice for reading all attributes from children by ID attributes using C # in the xml file below.

Thank,

 <?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>
+3
source share
2 answers

The following LINQ call should do the trick:

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

Descendants ( ) XML, "". First, , (, "ID", "2" ). , FirstOrDefault, null, . , Attributes .

, LINQ to XML - XML , ( LINQ).

+4

, . LINQ XML. Xpath :

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

, , API.

+3

Source: https://habr.com/ru/post/1771131/


All Articles