如何使用XSLT重定位XML中的结束标记

时间:2017-08-22 22:25:23

标签: xml xslt

我想知道如何使用XSLT在XML中重新定位结束标记。通常情况下,所有东西似乎都使用匹配来使事情有效,但这似乎有所不同。目标是在不直接更改XML文件的情况下获得所需的输出。我想只使用XSLT创建所需的输出。下面的代码很接近,但它不会关闭经理标记。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<x>
    <y>
        <z value="john" designation="manager"></z>
            <z value="mike" designation="associate"></z>
           <z value="dave" designation="associate"></z>
   </y>
</x>

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs" version="2.0">

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

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

<xsl:template match="*[contains(@designation, 'manager')]">
    <manager>
        <xsl:attribute name="value">
        <xsl:value-of select="@value"/>
        </xsl:attribute>
     </manager>
</xsl:template>

<xsl:template match="*[contains(@designation, 'associate')]">
    <associate>
        <xsl:value-of select="@value"/>
    </associate>
</xsl:template>

</xsl:stylesheet>

所需的输出:

<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee>
        <manager value="john">
            <associate>mike</associate>
            <associate>dave</associate>
        </manager>
    </employee>
</employees>

1 个答案:

答案 0 :(得分:0)

您的问题不是“重新定位结束标记”。它是通过将兄弟姐妹转换为父级和子级来重新排列XML树的层次结构。这可以通过以下方式完成:

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">
    <employees>
        <xsl:apply-templates/>
    </employees>
</xsl:template>

<xsl:template match="y">
    <employee>
        <xsl:apply-templates select="z[@designation='manager']"/>
    </employee>
</xsl:template>

<xsl:template match="z[@designation='manager']">
    <manager value="{@value}">
        <xsl:apply-templates select="../z[@designation='associate']"/>
    </manager>
</xsl:template>

<xsl:template match="z[@designation='associate']">
    <associate>
        <xsl:value-of select="@value"/>
    </associate>
</xsl:template>

</xsl:stylesheet>

请注意,这假设只有一个经理。否则,所有员工将被列入多个经理。

相关问题