Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

xml - XSLT - Comparing preceding-sibling's elements with current's node element

I have this XML file:

<recursos>
    <recurso url="http://w3c.com">
        <descripcion>Consorcio W3C</descripcion>
        <tipo>externo</tipo>
        <idioma>ingles</idioma>
        <contenido>General</contenido>
        <unidad>Unidad 2</unidad>
    </recurso>
    <recurso url="http://html.com">
        <descripcion>Especificación HTML</descripcion>
        <tipo>externo</tipo>
        <idioma>castellano</idioma>
        <contenido>HTML</contenido>
        <version>4.01</version>
        <unidad>Unidad 3</unidad>
    </recurso>
</recursos>

I want to compare one "recurso"'s preceding sibling element "unidad" with the "unidad" of the current "recurso" to check if they're different.

I was trying:

<xsl:if test="preceding-sibling::recurso[position()=1]::unidad != unidad">
</xsl:if>

But I know it's horribly wrong :( I hope you could help me, thank you very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Almost correct.

<xsl:if test="preceding-sibling::recurso[1]/unidad != unidad">
</xsl:if>

The :: is for axes, not for moving along a path ("making a location step"). In XPath terminology:

preceding-sibling::recurso[1]/unidad != unidad
'''''''''''''''''  ++++++++++ ++++++
                          ###
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~

'  = axis name       (optional, defaults to "child")
+  = node test       (required)
#  = predicate       (optional, for filtering)
~  = location step   (required at least once per select expression)

The [1] is a shorthand for [position()=1].

The child axis is implicit in a location step, so this

preceding-sibling::recurso[1]/unidad != unidad

is equivalent to this:

preceding-sibling::recurso[1]/child::unidad != unidad

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...