LINQ to XML基于多个属性在兄弟列表中查找位置

时间:2013-06-26 11:16:47

标签: linq-to-xml

给出以下结构。我如何获得兄弟姐妹中id =“3”的场景节点的位置,但只计算带有type =“chapter”的兄弟姐妹列表(在提供的示例中为1)?

<scene id="a">
      <scene id="b">
        <scene id="c" type="toc">
          <scene id="1" type="chapter"></scene>
          <scene id="2" type="other"></scene>
          <scene id="3" type="chapter"></scene> <!-- get the "sibling index" of this one, but based on id and type -->
          <scene id="4" type="chapter"></scene>
        </scene>
      </scene>
</scene>

编辑:

我自己的解决方案就像(抱歉不发布):

var sceneC = from scene in rootElement.Descendants("scene") where (string)scene.Attribute("id") == "c" select scene;
var index = -1;
foreach (var scene in sceneC.Elements("scene"))
{
    if (scene.Attribute("type").Value.Equals("chapter"))
    {
         index++;
         if (scene.Attribute("id").Value.Equals("3"))
         {
             break;
         }
     }
 }

但提供的解决方案似乎更优雅。

1 个答案:

答案 0 :(得分:1)

这很容易:

XElement rootElement = XElement.Parse(
@"<scene id=""a"">
      <scene id=""b"">
        <scene id=""c"" type=""toc"">
          <scene id=""1"" type=""chapter""></scene>
          <scene id=""2"" type=""other""></scene>
          <scene id=""3"" type=""chapter""></scene>
          <scene id=""4"" type=""chapter""></scene>
        </scene>
      </scene>
</scene>");
XElement sceneC = rootElement.Element("scene").Element("scene");
int theIndex = sceneC.Elements().TakeWhile(n => n.Attribute("id").Value != "3")
                     .Count(x => x.Attribute("type").Value == "chapter");