XSL交叉引用

5

我现在正在学习XSL,有一个关于交叉引用的问题。 我的目标XML文件结构如下:

<XML>
    <Model>
        <packedElement typ="class" id="1"/>
        <packedElement typ="class" id="2"/>
        <packedElement typ="class" id="3"/>
    </Model>
    <Elements>
        <Element idref="1">
            <Attributes comment="comment 1."/>
        </Element>
        <Element idref="2">
            <Attributes comment="comment 2."/>
        </Element>
        <Element idref="3">
            <Attributes comment="comment 3."/>
        </Element>
    </Elements>
</XML>

我想连接id=idref。我的目标是列出所有packedElements并打印它们的注释。你能帮我吗?

我尝试使用key函数解决它,但我并不成功。

编辑:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" encoding="UTF-8"/>

<xsl:key name="CommentK" match="Element" use="@idref"/>


<xsl:template match="XML">
<XML>
<xsl:apply-templates/>
</XML>
</xsl:template>

<xsl:template name="Start" match="packedElement">
<xsl:variable name="TEST" select="@id"/>
<xsl:variable name="Comment">
<xsl:call-template name="FindComment">
<xsl:with-param name="test2" select="@id"/>
</xsl:call-template>
</xsl:variable>
<content comment="{$Comment}" id ="{@id}" test="{$TEST}"></content>
</xsl:template>

<xsl:template name="FindComment">
<xsl:param name="test2"/>

<xsl:for-each select="key('CommentK', '$test2')">

<xsl:value-of select="Attributes/@comment"/>

</xsl:for-each>

</xsl:template>

</xsl:stylesheet>

XSLT版本为2.0。(顺便问一下,有人能告诉我.XSLT和.XSL之间的区别吗?)


你的尝试是什么样子的?你想要的结果是什么样子的? - JLRishe
我认为你的尝试几乎成功了,只是你使用了'$test2',它是字符串值"$test2"。它应该只是key('CommentK', $test2)。虽然我认为FindCommentfor-each有些过度了。Martin Honnen的答案很好。 - JLRishe
回答您帖子末尾的问题,.XSL和.XSLT都是XSLT文件的典型文件扩展名,使用哪一个都没有区别。 - JLRishe
1个回答

6

尝试

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="el-by-idref" match="Elements/Element" use="@idref"/>

<xsl:template match="XML">
  <xsl:copy>
    <xsl:apply-templates select="Model/packedElement"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="Model/packedElement">
  <content comment="{key('el-by-idref', @id)/Attributes/@comment}" id="{@id}" test="{@id}"/>
</xsl:template>



</xsl:stylesheet>

那样你就能获得:
<XML>
   <content comment="comment 1." id="1" test="1"/>
   <content comment="comment 2." id="2" test="2"/>
   <content comment="comment 3." id="3" test="3"/>
</XML>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接