简体   繁体   中英

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

<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:

using System.Xml;

you can use it to load the 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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