3

我有(这是一个例子)以下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]。不正确吗?如何使用当前元素引用的其他元素的值?

4

1 回答 1

3

是的,问题出在 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"/> 
于 2013-09-03T09:26:56.647 回答