如何为样本xml编写linq查询

时间:2017-06-05 13:53:38

标签: c# linq

如何使用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);

2 个答案:

答案 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;