选择其他引用的元素值

时间:2013-09-03 09:19:01

标签: xslt xpath

我有(这是一个例子)以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <list>
    <toot id="1">
      <value>A</value>
    </toot>
    <toot id="2">
      <value>B</value>
    </toot>
    <toot id="3">
      <value>C</value>
    </toot>
    <toot id="4">
      <value>D</value>
    </toot>
  </list>
  <otherlist>
    <foo>
      <value ref="2" />
    </foo>
    <foo>
      <value ref="3" />
    </foo>
  </otherlist>
</body>

以下XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/body">
    <xsl:apply-templates select="otherlist"/>
  </xsl:template>

  <xsl:template match="otherlist">
    <xsl:for-each select="foo">
      <result>
        <value><xsl:value-of select="/body/list/toot[@id=value/@ref]/value" /></value><!-- This is the important -->
        <ref><xsl:value-of select="value/@ref" /></ref>
      </result>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

这是制作/转换xml时的结果:

<?xml version="1.0" encoding="UTF-8"?>
<result>
  <value/>
  <ref>2</ref>
</result>
<result>
  <value/>
  <ref>3</ref>
</result>

问题是空的。我想得到的是:

<?xml version="1.0" encoding="UTF-8"?>
<result>
  <value>B</value>
  <ref>2</ref>
</result>
<result>
  <value>C</value>
  <ref>3</ref>
</result>

我认为问题是XPath /body/list/toot[@id=value/@ref]/value特别是条件[@id=value/@ref]。不对吗?如何使用其他元素的值是当前的参考?

1 个答案:

答案 0 :(得分:2)

是的,问题出现在上下文发生变化的XPath中,因此您实际上在寻找具有toot属性的@id元素和具有value属性的@ref子元素(实际上是foo的孩子),这两者是平等的。

您可以使用current()函数使其正常工作

<xsl:value-of select="/body/list/toot[@id=current()/value/@ref]/value"/>

或者您可以将@ref的值存储到变量中,并在谓词中使用此变量

<xsl:variable name="tmpRef" select="value/@ref" />
<xsl:value-of select="/body/list/toot[@id=$tmpRef]/value"/> 
相关问题