我有两个版本的 XmlDocument
版本 1
<?xml version="1.0" encoding="UTF-8"?>
<topElement>
<childElement1>Value</childElement1>
<childElement2>Value</childElement2>
...
</topElement>
版本 2
<?xml version="1.0" encoding="UTF-8"?>
<topElement>
<group1>
<childElement1>Value</childElement1>
<childElement2>Value</childElement2>
</group1>
<group2>
<childElement1>Value</childElement1>
<childElement2>Value</childElement2>
</group2>
</topElement>
在这两种情况下,我都需要获取所有子元素的所有值并将它们添加到 CustomObject 的集合中。 据我所知,这只能通过迭代来完成。
所以我得到了顶级节点,然后像这样:
CustomObject getLow(XmlNode node, CustomObject customObject)
{
foreach (XmlNode n in node.ChildNodes)
{
if (n.HasChildNodes == true)
{
getLow(n);
}
customObject.collection.Add(n.Name, n.InnerText);
}
return customObject;
}
毫无疑问这是错误的,请有人帮我在这两种情况下得到正确的结果吗?
最佳答案
您可以将 Xpath 与您的 XmlDocument 一起使用:
XmlDocument xmlDoc = new XmlDocument("yourxml.xml");
foreach (XmlNode childElement in xmlDoc.SelectNodes("//childElement"))
{
customObject.collection.Add(childElement.Name, childElement.InnerText);
}
关于c# - 获取 XmlDocument 的 "bottom"- C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14648032/