如何使用Linq-to-XML获取命名节点的后代?

时间:2013-05-15 22:37:52

标签: c# linq

我有以下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;

但是掩码查询返回null。

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:1)

使用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" );
相关问题