Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xslt 如何使用Xpath选择这些元素?_Xslt_Xpath - Fatal编程技术网

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

Xslt 如何使用Xpath选择这些元素?,xslt,xpath,Xslt,Xpath,我有一份文件,类似这样: <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>

我有一份文件,类似这样:

<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,只是我希望它们只是紧跟其后的元素

如果我在(node==1)上,那么我想选择node 2。 如果我在(节点==3)上,那么我不想选择任何内容。 如果我在(节点==4)上,那么我想选择5和6

我可以用xpath做这个吗?编辑:它位于XSL样式表select语句中


EDIT2:我不想在各种元素上使用node属性作为唯一标识符。我包含node属性只是为了说明我的观点。在实际的XML文档中,我没有用作唯一标识符的属性。xpath“后面的同级::UL[前面的同级::LI[1]/@node=current()/@node]” 键,这不是我想要的。

简短回答(假设current()是可以的,因为它被标记为xslt):

示例样式表:

<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>

A:
B:

祝你好运

解决方案可能是首先使用
以下同级节点收集以下所有节点:*
,获取其中的第一个节点并要求其为“B”节点

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

尽管@Chris Nielsen的答案是正确的,但在比较属性不唯一的情况下,它会留下不确定性。更正确的解决方法是:

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

这样可以确保前面的同级::A与当前的
A
相同,而不仅仅是比较一些属性值。除非您的属性保证是唯一的,否则这是唯一安全的方法。

+1;我本来想说下面的sibling::B[count(前面的sibling::A[1]| current())=1],但是你的方式似乎更容易理解。IMHO,确定节点标识的
count(…)
方法在语义上不如
generate-id()
方法,但偶尔我也会使用它。有点取决于上下文,但通常我更喜欢
generate-id()
,因为它更明确。提醒我,
current()
可以帮助定位语句以获得相对逻辑。
following-sibling::B[
  generate-id(preceding-sibling::A[1]) = generate-id(current())
]