Sindresvends
Sindresvends

Reputation: 190

Looping through all nodes in xml file with c#

I have an xml document with setup similiar to this:

<invoice>
   <IssueDate>2015-09-07</IssueDate>
   <InvoiceType>380<InvoiceType>
   <AccountingSupplierParty>
        <Party>
             <EndpointID></EndpointID>
             <PartyName>
                  <Name>Company test</Name>
             </PartyName>
        </Party>
    </AccountingSupplierParty>
</invoice>

This is just a little piece of the entire xml document, just to show how the file looks.

I would like to check all the elements too see if they have empty values, such as EndpointID in this example (I need to replace empty values with NA).

This is what I have so far:

public static void AddToEmptyElements()
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("testXml.xml");
    XmlNodeList nodes = xmlDoc.DocumentElement.ChildNodes;
    foreach (XmlNode node in nodes)
    {
        Console.WriteLine(node.Name);             
    }
}

However, this code will only loop through the childs of the root node and not all the grandchilds (or great grandchilds) such as the <Party> and <EndpointID> elements. How can I include these elements in the loop?

Upvotes: 6

Views: 20511

Answers (2)

roli09
roli09

Reputation: 981

As Jon Skeet already said, you could do this using LINQ to XML.

XDocument xml = XDocument.Load(path);
var emptyElements = xml.Descendants().Where(xe => String.IsNullOrEmpty(xe.Value));
foreach (var xe in emptyElements)
   xe.Value = "NA";

Upvotes: 6

dnanon
dnanon

Reputation: 550

I'm not in an environment to test code right now, but isn't it possible to write a recursive method to loop further down the nodes?

Something like this (untested code):

private static void handleNode(XmlNode node)
{
  if(node.HasChildNodes)
  {
    foreach(XmlNode child in node.ChildNodes)
    {
      handleNode(child);
    }
  }  
  else
    Console.WriteLine(node.Name);
}

then call this method in place of your Console.WrintLine()

Upvotes: 6

Related Questions