【发布时间】: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+<GetDescendants>d__a,而不是 XML 字符串。我似乎找不到任何方法可以返回匹配元素的 XML。
【问题讨论】:
标签: c# xml linq-to-xml