我必须使用XML源文件:
<person>
<firstname>John</firstname>
<lastname>Snow</lastname>
</person>
<person>
<firstname>Jonny</firstname>
<lastname>Hill</lastname>
</person>
<employee_list>
<employee>
<first>John</firstname>
<last>Snow</lastname>
</employee>
<employee>
<first>Jonny</first>
<last>Hill</last>
</employee>
</employee_list>
我需要连接这两个文件以及更改元素名称。到目前为止,我的XSLT文件如下所示:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:copy>
<xsl:apply-templates select="person"/>
<xsl:apply-templates select="document('2.xml')/person"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
但是输出文件中的间距是错误的,我没有添加其他元素并更改其他元素。
答案 0 :(得分:1)
请修改<xsl:template match="/">
,如下所示
<xsl:template match="/">
<employee_list>
<employee>
<xsl:apply-templates select="person/*" />
</employee>
<employee>
<xsl:apply-templates select="document('2.xml')/person/*" />
</employee>
</employee_list>
</xsl:template>
添加2个模板以修改元素名称即。 <firstname>
至<first>
和<lastname>
至<last>
。
<!-- Rename <firstname> to <first> -->
<xsl:template match="firstname">
<first>
<xsl:apply-templates />
</first>
</xsl:template>
<!-- Rename <lastname> to <last> -->
<xsl:template match="lastname">
<last>
<xsl:apply-templates />
</last>
</xsl:template>
完整的XSLT和输出如下
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />
<!-- Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<!-- Prepare output structure -->
<xsl:template match="/">
<employee_list>
<employee>
<xsl:apply-templates select="person/*" />
</employee>
<employee>
<xsl:apply-templates select="document('2.xml')/person/*" />
</employee>
</employee_list>
</xsl:template>
<!-- Rename <firstname> to <first> -->
<xsl:template match="firstname">
<first>
<xsl:apply-templates />
</first>
</xsl:template>
<!-- Rename <lastname> to <last> -->
<xsl:template match="lastname">
<last>
<xsl:apply-templates />
</last>
</xsl:template>
</xsl:stylesheet>
输出
<employee_list>
<employee>
<first>John</first>
<last>Snow</last>
</employee>
<employee>
<first>Jonny</first>
<last>Hill</last>
</employee>
</employee_list>