c# - 获取 XmlDocument 的 "bottom"- C#

标签 c# wpf xml iteration xmlnode

我有两个版本的 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/

相关文章:

c# - 访问 Azure 中的大文件

c# - SecurityManager.IsGranted() 行为

jquery - 在 wpf 中包含用于 Web 浏览器控制的 Jquery

c# - 错误 : Could not load file or assembly 'Microsoft. Practices.ServiceLocation,版本 = 1.0.0.0

XML 模式/命名空间

c# - 如何从 ListView 中获取所有项目到字符串 []?

c# - WPF:装饰控件(文本框)隐藏时不隐藏 Validation.ErrorTemplate

c# - 在 WPF 应用程序中单击按钮时从数据网格获取数据

sql-server - 埋在节点内的 XML 值

javascript - jQuery XML解析: 2 equally named XML tags.如何只取第一个?