如何从XML文档中获取某个名称的元素作为XML String? (使用XDocument)

时间:2014-10-15 10:32:28

标签: c# xml linq-to-xml

如何从XML文档中获取某个名称的元素作为XML String? (使用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+<GetDescendants>d__a而不是XML字符串。我似乎无法找到任何方法来回复匹配元素的XML。

3 个答案:

答案 0 :(得分:2)

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

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"));

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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