首页 文章

如何使用Xpath选择这些元素?

提问于
浏览
4

我有一份文件,如下:

<root>
   <A node="1"/>
   <B node="2"/>
   <A node="3"/>
   <A node="4"/>
   <B node="5"/>
   <B node="6"/>
   <A node="7"/>
   <A node="8"/>
   <B node="9"/>
</root>

使用xpath,如何选择连续跟随给定A元素的所有B元素?

它类似于跟随-silbing :: B,除了我希望它们只是紧随其后的元素 .

如果我在A(节点== 1),那么我想选择节点2.如果我在A(节点== 3),那么我想什么都不选 . 如果我在A(节点== 4),那么我想选择5和6 .

我可以在xpath中执行此操作吗?编辑:它在XSL样式表选择语句中 .


EDIT2:我没有't want to use the node attribute on the various elements as a unique identifier. I included the node attribute only for purposes of illustrating my point. In the actual XML doc, I don't有一个我用作唯一标识的属性 . 节点属性上的xpath "following-sibling::UL[preceding-sibling::LI[1]/@node = current()/@node]"键,这不是我想要的 .

3 回答

  • 5

    简短回答(假设current()没问题,因为这是标记的xslt):

    following-sibling::B[preceding-sibling::A[1]/@node = current()/@node]
    

    样式表示例:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml"/>
        <xsl:template match="/">
            <xsl:apply-templates select="/root/A"/>
        </xsl:template>
    
        <xsl:template match="A">
            <div>A: <xsl:value-of select="@node"/></div>
            <xsl:apply-templates select="following-sibling::B[preceding-sibling::A[1]/@node = current()/@node]"/>
        </xsl:template>
    
        <xsl:template match="B">
            <div>B: <xsl:value-of select="@node"/></div>
        </xsl:template>
    </xsl:stylesheet>
    

    祝好运!

  • 1

    虽然@Chris Nielsen的答案是正确的方法,但在比较属性不是唯一的情况下会留下不确定性 . 解决这个问题的更正确的方法是:

    following-sibling::B[
      generate-id(preceding-sibling::A[1]) = generate-id(current())
    ]
    

    这确保 preceding-sibling::A 与当前 A 相同,而不是仅仅比较某些属性值 . 除非您拥有保证唯一的属性,否则这是唯一安全的方法 .

  • 3

    解决方案可能是首先使用 following-sibling::* 收集所有以下节点, grab 第一个节点并要求它为'B'节点 .

    following-sibling::*[position()=1][name()='B']
    

相关问题