如何找到作为具有特定属性的元素的子元素的祖先或自我? [英] How to find ancestor-or-self that is a child of an element with particular attribute?

查看:26
本文介绍了如何找到作为具有特定属性的元素的子元素的祖先或自我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个非常通用的 XML 结构,其中一切都是一个项目(无论如何与这个问题相关的一切).

I'm working with a very generic XML structure, where everything is an item (well everything relevant to this question anyway).

基于知道我当前所在的 item 元素以及作为我正在寻找的节点的父级的 item 元素,我需要找到一个 item.我有一个可用的 xpath,但它相当占用资源,我正在寻找更优雅、更便宜的东西.

Based on knowing the item element I'm currently on and the item element that is the parent of the node I'm looking for, I need to find an item. I have a working xpath, but it's fairly resource intensive and I'm looking for something more elegant and cheaper.

item key=a 节点是我要查找的元素的父节点(尽管它实际上不是文档根的子节点)

The item key=a node is the parent of the element I'm looking for (though it's not actually a child of the document root)

XML:

<root>
    <item key="a">
        <item key="b">
            <item key="c">
                <item key="d"/>
            </item>
        </item>
        <item key="e">
            <item key="f">
                <item key="g"/>
            </item>
        </item>
    </item>
</root>

实际的 XML 更深,分支更多.

The actual XML is much deeper and with far more branching.

例如,如果我在 key=g、e 或 f 的项目上,我需要返回 key=e 的项目.如果我在使用键 b、c 或 d 的项目上,我需要使用键=b 返回该项目.

So for instance, if I'm on the item with key=g, e or f I need to return the item with key=e. If I'm on the item with key b,c or d I need to return the item with key=b.

我正在使用这个有效的 xpath,但是在祖先-后代轴上向上然后向下返回似乎比我需要的行程要长得多.

I'm using this xpath, which is working, but going up and then back down the ancestor-descendant axis seems a far longer trip than I need.

current()
   /ancestor-or-self::item[@key='a']
      /item[descendant-or-self::* = current()]

有没有更简单的方法来做到这一点,记住我只知道 1)我所在的节点和 2)我正在寻找的节点的父节点的关键属性?

Is there a simpler way of doing this, bearing in mind that I only know 1) the node I'm on and 2) the key attribute of the parent of the node I'm looking for?

只是为了详细说明:XML 是 Sitecore 生成的,我实际上并没有使用 current() 函数,我使用的是 sc_currentitem 参数来设置我需要开始处理的起始节点.

Just for detail's sake: The XML is Sitecore generated, I'm not actually using the current() function, I'm using the sc_currentitem parameter to set the start node I need to begin processing at.

提前致谢.

推荐答案

使用:

ancestor-or-self::*[parent::item[@key='a']]

这篇关于如何找到作为具有特定属性的元素的子元素的祖先或自我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆