Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 901
Sindresvends Avatar asked Sep 21 '15 08:09

Sindresvends


People also ask

Which element is used to loop through the XML elements?

Looping through XML element c#

How do I count nodes in XML?

Count the XML elements (XPath)newXPath(); NodeList nodes = (NodeList) xpath. evaluate("//staff", doc, XPathConstants. NODESET); int count = nodes. getLength();

Which class is used in C for writing an XML file?

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items.


2 Answers

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

like image 115
dnanon Avatar answered Oct 05 '22 23:10

dnanon


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";
like image 36
roli09 Avatar answered Oct 05 '22 23:10

roli09