【问题标题】:Getting to "bottom" of XmlDocument - C#到达 XmlDocument 的“底部” - C#
【发布时间】:2013-02-01 14:04:42
【问题描述】:

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

在这两种情况下,我都需要获取所有 childElements 的所有值并将它们添加到 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;
}

毫无疑问这是错误的,请有人帮我在这两种情况下都得到正确的结果吗?

【问题讨论】:

  • 好吧,也许 While 循环不是一个好主意 =) 我应该改用 if 语句吗?
  • 什么是getLow(XmlNode xmlNode)
  • 如果n 有子节点,您将永远不会离开while 循环。
  • @t3hn00b 好吧,我的错,在那里犯了一个错误。基本上有方法自己调用。

标签: c# wpf xml iteration xmlnode


【解决方案1】:

您可以将 Xpath 与您的 XmlDocument 一起使用:

XmlDocument xmlDoc = new XmlDocument("yourxml.xml");
foreach (XmlNode childElement in xmlDoc.SelectNodes("//childElement"))
{
    customObject.collection.Add(childElement.Name, childElement.InnerText);
}

【讨论】:

    【解决方案2】:

    循环不是唯一的方法 - 另一种方法是生成具有 XML 属性的自定义类的对象图,并使用 XML 序列化程序将 XML 转换为对象图。

    详情请见http://msdn.microsoft.com/en-gb/library/system.xml.serialization.xmlserializer.aspx

    另一种方法是使用 XDocument 并使用 linq 直接从 XDocument 中查询您想要的值。

    Using Linq and XDocument, can I get all the child elements under parent tag?

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您应该能够使用一些 xPath 来获取您正在寻找的节点。

      试试类似的东西

      node.SelectNodes("//*[count(child::*)=0]")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 2013-09-12
        • 1970-01-01
        • 2010-10-24
        • 2012-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多