使用XSL加入XML节点

时间:2016-10-12 16:16:49

标签: xml xslt

如何使用docid字段将/ Document / Head / Signature节点与相应的/ Document / Image节点连接,以便在同一块中将内容输出到HTML?

<?xml version="1.0"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Head>
        <Account>Fred123</Account>
        <accountName>Fred Blogs Ltd</accountName>
        <Signature>
            <sigName>Fred Bloggs</sigName>
            <docid>39215896554.0</docid>
        </Signature>
    </Head>
    <Image>
        <docid>39215896554.0</docid>
        <docTitle>Fred Bloggs Signature</docTitle>
    </Image>
    <Image>
        <docid>121212121212.0</docid>
        <docTitle>Jo Smith Signature</docTitle>
    </Image>
</Document>

示例输出:

<div id="sig">
    Signature Name: Fred Bloggs<br />
    Signature Title: Fred Bloggs Signature
</div>

我已尝试使用xsl:for-each的一些方法,但我有一些不太正确的事情......这是一次尝试:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <html>
        <head>
        </head>
        <body>
            <h1>Page</h1>
            <xsl:for-each select="/Document/Head/Signature[docid = /Document/Image/docid]">
                <h4><xsl:value-of select="sigName"/></h4>
                <h4><xsl:value-of select="docTitle"/></h4>
            </xsl:for-each>
        </body>
    </html>
</xsl:template>

1 个答案:

答案 0 :(得分:2)

你有正确的条件,显然然后从你需要再次引用它的引用元素输出数据:

<xsl:template match="/">
    <html>
        <head>
        </head>
        <body>
            <h1>Page</h1>
            <xsl:for-each select="/Document/Head/Signature[docid = /Document/Image/docid]">
                <h4><xsl:value-of select="sigName"/></h4>
                <h4><xsl:value-of select="/Document/Image[docid = current()/docid]/docTitle"/></h4>
            </xsl:for-each>
        </body>
    </html>
</xsl:template>

我会使用密钥

<xsl:key name="image-ref" match="Image" use="docid"/>
<xsl:template match="/">
    <html>
        <head>
        </head>
        <body>
            <h1>Page</h1>
            <xsl:for-each select="/Document/Head/Signature[key('image-ref', docid)]">
                <h4><xsl:value-of select="sigName"/></h4>
                <h4><xsl:value-of select="key('image-ref', docid)/docTitle"/></h4>
            </xsl:for-each>
        </body>
    </html>
</xsl:template>