繁体   English   中英

如何编写示例XML的linq查询

[英]How to write linq query for sample xml

如何使用linq(root / doc / files / file)从此类xml中获取元素的值集合:

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

使用Descendants方法:

var result= root.Descendants("file").Select(e=>e.Value);

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM