Search code examples
c#xmlnodelist

Reading XMLNodeList


I have an odd issue where I am trying to read a node in an xml document but I need to read the nodes inner text after a node that I can find based on the inner text.

I have an xml document

<?xml version="1.0"?>
<DataFeedObject xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TransactionID>a4b0ecc1-2d28-49f4-b9c7-caec861aa80d</TransactionID>
  <ApplicationID>b0926229-3209-4881-8cf3-cf4a88756a7f</ApplicationID>
  <TransactionDateTime>2016-04-25T21:03:49.5805295Z</TransactionDateTime>
  <DataItems>
    <DataItem>
      <Name>Account_Type</Name>
      <Value>Cash</Value>
    </DataItem>
    <DataItem>
      <Name>Account_Type_MarginDetails</Name>
    </DataItem>
    <DataItem>
      <Name>Agent_FirstName</Name>
      <Value>Jane</Value>
    </DataItem>
    <DataItem>
      <Name>Agent_IDNumber</Name>
      <Value>12547896</Value>
    </DataItem>
    <DataItem>
      <Name>Agent_LastName</Name>
      <Value>Doe</Value>
    </DataItem>
 </DataItems>
....

I can loop through the nodes and find the node Agent_LastName

node.SelectSingleNode("Name").InnerText == "Agent_LastName"

but I need the text that is in the Value tag directly after this node. How can I step to the next node.

I could just set a flag set the flag when I find the node ant then on the next iteration grab the inner text but this seems sloppy.


Solution

  • Use Xpath

    XmlDocument doc = new XmlDocument();
    Doc.load(@"doc.xml");
    XmlElement root = doc.DocumentElement;
    var node = root.SelectSingleNode("/DataFeedObject/DataItems/DataItem/[Name = 'Agent_LastName']/Value");