0

给定以下结构。如何在兄弟姐妹中获得 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;
         }
     }
 }

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

4

1 回答 1

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");
于 2013-06-26T21:10:47.810 回答