6

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?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Sindresvends
  • 180
  • 1
  • 1
  • 10
  • 1
    Yeah sure, use recursion. – Patrick Hofman Sep 21 '15 at 08:12
  • check this http://stackoverflow.com/questions/2915294/iterating-through-all-nodes-in-xml-file – Gaby Sep 21 '15 at 08:16
  • 5
    As a side-note, LINQ to XML generally makes life a lot simpler. Your problem is definitely soluble with `XmlDocument`, but if you could use LINQ to XML instead, it would be a one-liner... – Jon Skeet Sep 21 '15 at 08:19
  • For xml recursion I like the code in following website for adding xml to a treeview. Used the code a number of times before. http://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng Sep 21 '15 at 08:25

2 Answers2

6

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

dnanon
  • 540
  • 5
  • 19
6

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";
roli09
  • 817
  • 1
  • 8
  • 20