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 to use a foreach on its child nodes.
public void LoadXML() {
if (File.Exists("Data.xml")) {
//Reading XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Data.xml");
//Think something needs to reference Child nodes, so i may Foreach though them
XmlNodeList dataNodes = xmlDoc.SelectNodes("//FieldData");
TagContents[] ArrayNode;
foreach(XmlNode node in dataNodes) {
int Count = 0;
//int Max = node.ChildNodes.Count;
ArrayNode = new TagContents[Max];
ArrayNode[Count].TagName = node.Name;
ArrayNode[Count].TagValue = node.SelectSingleNode(ArrayNode[Count].TagName).InnerText;
Count = Count + 1;
}
} else {
MessageBox.Show("Could not find file Data.xml");
}
}
My XML Looks Something like:
<?xml version="1.0"?>
<FieldData>
<property_details_branch IncludeInPDFExport="Yes" Mod="20010101010101"/>
<property_details_inspection_date IncludeInPDFExport="Yes" Mod="20120726200230">20120727220230+0200</property_details_inspection_date>
<property_details_type_of_ownership IncludeInPDFExport="Yes" Mod="20120726134107">Freehold</property_details_type_of_ownership>
</FieldData>
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)
{
I generally prefer Linq-To-Xml for this kind of thing:
var doc = XDocument.Load("XMLFile1.xml");
foreach (var child in doc.Element("FieldData").Elements())
{
Console.WriteLine(child.Name);
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With