【问题标题】:How can I get elements of a certain name from an XML document as an XML String? (with XDocument)如何从 XML 文档中获取特定名称的元素作为 XML 字符串? (使用 XDocument)
【发布时间】:2014-10-15 10:32:28
【问题描述】:

如何从 XML 文档中获取特定名称的元素作为 XML 字符串? (使用 XDocument)

也就是说,我有这个:

<root>
    <orange id="orange1"></orange>
    <orange id="orange2"></orange>
    <orange id="orange3"></orange>

    <apple id="apple1"></apple>
    <apple id="apple2"></apple>
    <apple id="apple3"></apple>
</root>

我怎样才能只获取苹果的 XML?即那三行的XML字符串?

我当前的代码是:

using (TextReader reader = File.OpenText(xmlFilePath))
{
    XDocument xmlDocument = XDocument.Load(reader);
    string items = xmlDocument.Descendants("apple").ToString();
}

...但在此示例中,items 最终为:System.Xml.Linq.XContainer+&lt;GetDescendants&gt;d__a,而不是 XML 字符串。我似乎找不到任何方法可以返回匹配元素的 XML。

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    问题是您在调用Descendants() 的结果上调用ToString()。目前还不清楚您期望做什么,但您正在正确获取元素。例如:

    using (TextReader reader = File.OpenText(xmlFilePath))
    {
        // Any reason for not using XDocument.Load(xmlFilePath)?
        XDocument xmlDocument = XDocument.Load(reader);
        var items = xmlDocument.Descendants("apple");
        foreach (var item in items)
        {
            Console.WriteLine(item.Attribute("id").Value); // Or whatever
        }
    }
    

    如果要将每个XElement 转换为字符串的结果连接起来,可以使用:

    var items = string.Join("", xmlDocument.Descendants("apple"));
    

    var items = string.Concat(xmlDocument.Descendants("apple"));
    

    【讨论】:

    • 你是对的,没有正确阅读问题。感谢您的提醒。
    • 我正在尝试合并两个 XML 文件(一个模板和一个带有一些数据项的不同 xml 文件)。我不需要对实际值进行任何访问,也不想使用对象,因为“在现实生活中”XML 比我的示例显示的要复杂得多(例如,“apple”元素是一种深层树结构) .
    • @NickG:“我不想使用对象”是什么意思?如果您处理 XElement 对象而不是字符串,那么您的代码可能会更加简洁...
    • 我知道这似乎是错误的,但在这种特殊情况下,我的程序根本不关心文件中的数据(它只是一个预处理器)——它实际上只需要合并它们连同任何名为“apples”的标记内的所有 XML 替换单独文件中的占位符标记。 XML 上的所有实际工作都在不同的应用程序中完成,并将它们反序列化为对象。
    • 所以你的第二个代码块正是我需要的——非常感谢!
    【解决方案2】:

    使用String.Concat(xmlDocument.Descendants("apple"))

    【讨论】:

      【解决方案3】:

      您在一组 xml 元素上使用ToString(),因此您的结果。如果我正确阅读了您的要求,您需要以下内容:

      var items = String.Join(Environment.NewLine,
                              xmlDocument.Descendants("apple")
                                         .Select(e => e.ToString()));
      

      【讨论】:

        猜你喜欢
        • 2011-05-30
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 1970-01-01
        • 2019-04-14
        相关资源
        最近更新 更多