I have an XML File and i would like to iterate though each child node gathering information.
Here is my C# code it only picks up one node, the FieldData i would like
You can do it like this:
XDocument doc = XDocument.Load(@"Data.xml");
TagContents[] ArrayNode = doc.Root
.Elements()
.Select(el =>
new TagContents()
{
TagName = el.Name.ToString(),
TagValue = el.Value
})
.ToArray();
public void ValidateXml(string[] Arrays)
{
foreach (var item in Arrays)
{
Xdoc.Load(item);
XmlNodeList xnList = Xdoc.SelectNodes("FirstParentNode");
if (xnList.Count > 0)
{
foreach (XmlNode xn in xnList)
{
XmlNodeList anode = xn.SelectNodes("SecondParentNode");
if (anode.Count > 0)
{
foreach (XmlNode bnode in anode)
{
string InnerNodeOne = bnode["InnerNode1"].InnerText;
string InnerNodeTwo = bnode["InnerNode1"].InnerText;
}
}
else
{
ErrorLog("Parent Node DoesNot Exists");
}
}
}
else
{
ErrorLog("Parent Node DoesNot Exists");
}
}
//then insert or update these values in database here
}
Or you use recursion:
public void findAllNodes(XmlNode node)
{
Console.WriteLine(node.Name);
foreach (XmlNode n in node.ChildNodes)
findAllNodes(n);
}
Where do you place the payload depends on what kind of search you want to use (e.g. breadth-first search, depth-first search, etc; see http://en.wikipedia.org/wiki/Euler_tour_technique)
To iterate through each and every child node, sub-child node and so on, We have to use Recursion
. In case someone have the same requirement as I had, I achieved this something like below -
public string ReadAllNodes(XmlNode node)
{
if (node.ChildNodes.Count > 0)
{
foreach (XmlNode subNode in node)
{
//Recursion
ReadAllNodes(subNode);
}
}
else //Get the node value.
{
finalText = finalText + node.InnerText + System.Environment.NewLine;
}
return finalText;
}
Just touching on @Waynes answer, which worked well. I used the below code to push further into the child nodes in my xml
foreach (var child in doc.Element("rootnodename").Element("nextchildnode").Elements())
{
//do work here, probs async download xml content to file on local disc
}
You're iterating the FieldData nodes and you have only one. To iterate its child nodes write:
foreach (XmlNode node in dataNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{