开发者

How do I get an XML node with xpath in a loop, based on an attribute with the same name as the attribute in the tree I'm searching?

开发者 https://www.devze.com 2023-01-18 15:51 出处:网络
I cant really formulate that better, so I\'ll go with an example instead: XML: <root> <foo> <bar id=\"1\">sdf</bar>

I cant really formulate that better, so I'll go with an example instead:

XML:

<root>
  <foo>
    <bar id="1">sdf</bar>
    <bar id="2">sdooo</bar
  </foo>
  <feng>
    <heppa id="4">hihi</heppa>
    <heppa id="2">sseeapeea</heppa>
    <heppa id="1">....</heppa>
  </feng>
</root>

XSLT:

<xsl:for-each select="/root/foo/bar">
  <p>
    <xsl:value-of select="." />: <xsl:value-of开发者_StackOverflow社区 select="/root/feng/heppa[@id = @id]" />
  </p>
</xsl:for-each>

Desired output:

<p>sdf: ....</p>
<p>sdooo: sseeapeea</p>

Actual output:

<p>sdf: hihi</p>
<p>sdooo: hihi</p>


For selecting nodes with XPath 1.0 only, you need to do a node set comparison:

/root/feng/heppa[@id=/root/foo/bar/@id]

Of course, this has NxM complexity (as the others XSLT solutions)

With XSLT 1.0 you should use keys because there are cross references:

<xsl:key name="kBarById" select="bar" use="@id"/>

<xsl:template match="/root/feng/heppa[key('kBarById',@id)]">       
    <p>       
        <xsl:value-of select="concat(key('kBarById',@id),': ',.)"/>
    </p>       
</xsl:template> 


I assume you mean /root/foo/bar since /root/foo elements don't have id.

You're comparing the @id with itself, so of course it's true for the first node examined. You can use current() to reference the current node in an expression:

<xsl:for-each select="/root/foo/bar">
  <p>
    <xsl:value-of select="." />: <xsl:value-of select="/root/feng/heppa[@id = current()/@id]" />
  </p>
</xsl:for-each>


Another solution is to read the id attribute into a variable.

<xsl:for-each select="/root/foo/bar">
    <xsl:variable name="id" select="@id"/>
    <p>
        <xsl:value-of select="." />: <xsl:value-of select="/root/feng/heppa[@id = $id]" />
    </p>
</xsl:for-each>

This might be handier, if your real use case is more complicated and you need to use the value of the id multiple times in this for-each section.

0

精彩评论

暂无评论...
验证码 换一张
取 消