簡體   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