如何使用xslt在第二个和第三个xml元素中显示具有相同名称的文本

时间:2017-08-13 01:03:18

标签: xml xslt

我想知道是否可以使用xslt使用xml部分的值来显示名称。如果那是不可能的,那么我如何使用xslt简单地显示名称?我还想知道xslt可以更改xml中的元素名称吗?

我的xml就是这个

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="myxmltest.xsl type="text/xsl" version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ?>

<x>
 <y>
  <z value="mike"></z>
  <z value="john"></z>
  <z value="dave"></z>
 </y>
</x>

我的xsl就是这个

<?xml version="1.0"?>

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

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

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

<xsl:template match="z">
<xsl:apply-templates select="z[1]" />mike
</xsl:template>

<xsl:template match="z">
<xsl:apply-templates select="z[2]" />john
</xsl:template>

<xsl:template match="z">
<xsl:apply-templates select="z[3]" />dave
</xsl:template>

</xsl:stylesheet>

xml中的所需结果是:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="myxmltest.xsl type="text/xsl" version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ?>

<boss>
 <manager>
  <employee value="mike">mike</employee>
  <employee value="john">john</employee>
  <employee value="dave">dave</employee>
 </manager>
</boss>

1 个答案:

答案 0 :(得分:0)

您展示的结果可以通过以下方式轻松完成:

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:template match="x">
    <boss>
        <xsl:apply-templates/>
    </boss>
</xsl:template>

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

<xsl:template match="z">
    <employee value="{@value}">
        <xsl:value-of select="@value"/>
    </employee>
</xsl:template>

</xsl:stylesheet>