XSLT:xsl:for-each和xsl-choose检索元素的内容并将其放在其他地方?

时间:2015-10-19 15:23:03

标签: xml xslt xpath

我有这种XML结构:

<book>
    <chap>
        <dev>
            <p>This is some text<apnb id="N1"/>blah blah blah</p>
            <p>...</p>
            <p>...</p>
            <quote>...</quote>
        </dev>
        <defnotes>
            <ntb id="N1">This is the footnote corresponding to the element apnb</ntb>
        </defnotes>
    </chap>
</book>

我需要做的是(因为我有近900个apbn标签):对于每个带有某个@id的apbn标签,我想用相同的@id显示相应ntb标签的内容。我的猜测是使用xsl:for-each select =&#34; apbn&#34;像xsl里面的测试:选择。当apbn标签的@id与ntb标签的@id相同时,则显示ntb标签的内容。我认为它可行,但直到现在我还没有成功实现它。

非常感谢。 FLO。

1 个答案:

答案 0 :(得分:1)

解决交叉引用的最佳方法是使用 key

您没有指定输入的外观。在此示例中,脚注将插入方括号内的文本中:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="ntb" match="ntb" use="@id" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="apnb">
    <xsl:text> [</xsl:text>
        <xsl:value-of select="key('ntb', @id)"/>
    <xsl:text>] </xsl:text>
</xsl:template>

<xsl:template match="defnotes"/>

</xsl:stylesheet>

测试输入:

<book>
  <chap>
    <dev>
      <p>This is some text<apnb id="N1"/>blah blah blah</p>
      <p>...</p>
      <p>This is another text<apnb id="N2"/>blah blah blah</p>
      <p>...</p>
      <quote>...</quote>
    </dev>
    <defnotes>
      <ntb id="N1">This is the first footnote</ntb>
    </defnotes>
    <defnotes>
      <ntb id="N2">This is the second footnote</ntb>
    </defnotes>
  </chap>
</book>

<强>结果:

<?xml version="1.0" encoding="UTF-8"?>
<book>
   <chap>
      <dev>
         <p>This is some text [This is the first footnote] blah blah blah</p>
         <p>...</p>
         <p>This is another text [This is the second footnote] blah blah blah</p>
         <p>...</p>
         <quote>...</quote>
      </dev>
   </chap>
</book>