簡體   English   中英

如何使用Linq-to-XML獲取命名節點的后代?

[英]How do I get the descendants of a named node using Linq-to-XML?

我有以下XML:

<!--Gaffer Tape Regions--> 
  <masks>
   <mask name="Serato">
    <rectangle>
      <xPosition>100</xPosition>
      <yPosition>100</yPosition>
      <height>100</height>
      <width>100</width>
     </rectangle>
     <rectangle>
        <xPosition>500</xPosition>
        <yPosition>500</yPosition>
        <height>100</height>
        <width>100</width>
    </rectangle> 
  </mask>   
  <mask name="Traktor">
    <rectangle>
      <xPosition>180</xPosition>
      <yPosition>70</yPosition>
      <height>200</height>
      <width>300</width>
     </rectangle>
     <rectangle>
        <xPosition>500</xPosition>
        <yPosition>500</yPosition>
        <height>50</height>
        <width>160</width>
    </rectangle>   
  </mask>
 </masks>

我想檢索其名稱為“ Serato”的mask元素下的所有矩形元素。

在Linq to XML中做到這一點的最佳方法是什么?

編輯:添加的代碼不起作用

目前正在嘗試:

XDocument maskData = XDocument.Load(folderPath + @"\masks.xml");


            var masks =
                    from ma in maskData.Elements("mask")
                    where ma.Attribute("name").Value == "Serato"
                    from rectangle in ma.Elements("rectangle")
                    select rectangle;

但是masks查詢返回null。

var xml = XElement.Parse(s);
var rectangles = 
    from mask in xml.Elements("mask")
    where mask.Attribute("name").Value == "Serato"
    from rectangle in mask.Elements("rectangle")
    select rectangle;

使用LINQ to XML查詢時,需要包括Root節點。 如果包含“根”節點,則編輯后的查詢將起作用:

var masks =
    from ma in maskData.Root.Elements( "mask" ) // <-- notice .Root.
    where ma.Attribute( "name" ).Value == "Serato"
    from rectangle in ma.Elements( "rectangle" )
    select rectangle;

或使用方法鏈:

var rect = maskData.Root.Elements( "mask" )
        .Where( x => x.Attribute( "name" ).Value == "Serato" )
        .Elements( "rectangle" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM