我有一个XML文件,我想迭代每个子节点收集信息。
这是我的C#代码,它只选择一个节点,FieldData我想在其子节点上使用foreach。
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");
}
}
我的XML看起来像:
<?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>
答案 0 :(得分:21)
您正在迭代FieldData节点,而您只有一个。要迭代其子节点,请写:
foreach (XmlNode node in dataNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
答案 1 :(得分:6)
我通常更喜欢Linq-To-Xml这样的事情:
var doc = XDocument.Load("XMLFile1.xml");
foreach (var child in doc.Element("FieldData").Elements())
{
Console.WriteLine(child.Name);
}
答案 2 :(得分:2)
你可以这样做:
XDocument doc = XDocument.Load(@"Data.xml");
TagContents[] ArrayNode = doc.Root
.Elements()
.Select(el =>
new TagContents()
{
TagName = el.Name.ToString(),
TagValue = el.Value
})
.ToArray();
答案 3 :(得分:0)
刚刚接触@Waynes的答案,该答案效果很好。我使用下面的代码进一步推进我的xml
中的子节点foreach (var child in doc.Element("rootnodename").Element("nextchildnode").Elements())
{
//do work here, probs async download xml content to file on local disc
}
答案 4 :(得分:0)
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
}
答案 5 :(得分:0)
要遍历每个子节点,子子节点等,我们必须使用Recursion
。如果有人有与我相同的要求,我可以达到以下要求-
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;
}