如何使用xslt添加'join'xml文件?

时间:2010-11-05 12:45:13

标签: xml xslt

我找到了几个类似的答案,但我不明白为什么这不起作用; 这是我真实问题的精简版,但我测试了它并得到了相同的结果;

test1.xml

<?xml version="1.0" encoding="UTF8"?>
<fieldList>
<sourceField name="SourceTime">
<fid>REC_TIME</fid>
</sourceField>
</fieldList>

lookup.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
<field  name="REC_TIME" fid_type="DATE"/>
</data>

joinTest.xsml

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" media-type="text/plain"/>
<xsl:variable name="fieldDict" select="'lookup.xml'" />
<xsl:template match="/fieldList/*[fid]">
<xsl:variable name="id" select="current()"/>
<xsl:value-of select="$id"/>
<xsl:for-each select="document($fieldDict)/data/field[@name = $id]">
<xsl:value-of select="@type"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

现在,如果我将xpath更改为[@name],我会得到

REC_TIME
MONKEY

这是我想要的结果,但显然真正的文件有多个条目,所以我需要过滤器实际工作!

我正在使用Linux上的xsltproc进行测试

xsltproc --version
Using libxml 20705, libxslt 10124 and libexslt 813
xsltproc was compiled against libxml 20632, libxslt 10124 and libexslt 813
libxslt 10124 was compiled against libxml 20632
libexslt 813 was compiled against libxml 20632

非常感谢。

1 个答案:

答案 0 :(得分:2)

此转换是对XSLT代码的最简单修正,产生想要的结果

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my"
>
    <xsl:output method="xml" encoding="UTF-8" media-type="text/plain"/>

    <my:lookup>
        <data>
          <field  name="REC_TIME" fid_type="DATE"/>
        </data>
    </my:lookup>

    <xsl:variable name="fieldDict" select="document('')/*/my:lookup" />

    <xsl:template match="/fieldList/*[fid]">
        <xsl:variable name="id" select="fid"/>
        <xsl:value-of select="$id"/>
        <xsl:text> </xsl:text>
        <xsl:for-each select="$fieldDict/data/field[@name = $id]">
            <xsl:value-of select="@fid_type"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

将此转换应用于提供的XML文档

<fieldList>
    <sourceField name="SourceTime">
        <fid>REC_TIME</fid>
    </sourceField>
</fieldList>

生成了想要的结果

REC_TIME DATE

请注意

  1. 您的代码唯一重大更改是$id的定义。

  2. 通常对于此类操作,建议使用密钥以加快处理速度