如何使用linq从这样的xml中获取元素值的集合 (根/ DOC /文件/文件):
<root>
<doc>
<files>
<file>1</file>
<file>2</file>
<file>3</file>
</files>
</doc>
<doc>
<files>
<file>4</file>
<file>5</file>
<file>6</file>
</files>
</doc>
</root>
从那个查询我想:
1
2
3
4
5
6
这是我到目前为止编写的代码的开头。
string xmlIn = "<root> "+
" <doc>"+
" <files>"+
" <file>1</file>"+
" <file>2</file>"+
" <file>3</file> "+
" </files> "+
" </doc>"+
" <doc>"+
" <files>"+
" <file>4</file>"+
" <file>5</file>"+
" <file>6</file> "+
" </files> "+
" </doc>"+
" </root>";
var xml = XDocument.Parse(xmlin);
答案 0 :(得分:3)
使用Descendants
方法:
var result= root.Descendants("file").Select(e=>e.Value);
答案 1 :(得分:1)
C#/ .NET有一个XML解串器/解析器:
using System.Xml;
您可以使用它来加载XML:
//using a previously created stream that holds an XML document
XDocument xdoc = XDocument.Load(xmlstream);
然后,您可以使用LINQ选择所需内容:
// this example looks for a tag called 'object' and then collects all
// the objects of type 'cluster'
var clusters = from cluster in _XDoc.Descendants("object")
where cluster.Attribute("type").Value == "cluster"
select cluster;