Search code examples
c#xpathxmldocument

Get specific values from Xml


I don't how to extract the values from XML document, and am looking for some help as I'm new to C#

I am using XmlDocument and then XmlNodeList for fetching the particular XML document

Here is my code

XmlNodeList XMLList = doc.SelectNodes("/response/result/doc");

And my XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>
  <doc>
    <long name="LoadID">494</long>
    <long name="EventID">5557</long>
    <str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
  <doc>
    <long name="LoadID">774</long>
    <long name="EventID">5558</long>
    <str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
</result>
</response>

In this i have to fetch every the XMLData data that is under every doc tag and i have to fetch last doc tag EventID.


Solution

  • var xml = XDocument.Parse(xmlString);
    
    var docs = xml.Root.Elements("doc");
    
    var lastDocEventID = docs.Last()
                             .Elements("long")
                             .First(l => (string)l.Attribute("name") == "EventID")
                             .Value;
    
    Console.WriteLine ("Last doc EventId: " +lastDocEventID);
    
    foreach (var doc in docs)
    {
        Console.WriteLine (doc.Element("str").Element("TransactionDate").Value);
    }
    

    prints:

    Last doc EventId: 5558
    2014-05-28T14:17:31.2186777-06:00
    2014-05-28T14:17:31.2186777-06:00