简体   繁体   English

如何编写示例XML的linq查询

[英]How to write linq query for sample xml

How to get the collection of values of elements from such an xml, using linq (root/doc/files/file): 如何使用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>

From that query I would like to have: 从该查询,我想拥有:

1
2
3
4
5
6

Here is the beginning of the code I have written so far. 这是我到目前为止编写的代码的开头。

    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 has an XML deserializer/parser: C#/。NET具有XML反序列化器/解析器:

using System.Xml;

you can use it to load the XML: 您可以使用它来加载XML:

  //using a previously created stream that holds an XML document
     XDocument xdoc =  XDocument.Load(xmlstream);

You can then use LINQ to select what you want: 然后,您可以使用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