XSLT嵌套到xml的平面结构

时间:2014-06-14 19:30:26

标签: xml xslt

使用xslt我想从:

转换xml文档
<element1>val1</element1>
<element2>
    <element3> value </element3>
    <element4> value </element4>
<element2>

到xml,如:

<element1>val1</element1>
<element3> value </element3>
<element4> value </element4>

我想删除<element2>,因为它包含&#34;儿童元素&#34;和所有其他元素创建为平面元素。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

以下样式表将删除所有具有子元素的元素(根元素除外),仅返回叶子节点的“平面”列表:

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="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*/*[*]">
    <xsl:apply-templates select="*"/>
</xsl:template>

</xsl:stylesheet>

应用于以下测试输入

<world>
    <Europe>
        <Germany>
            <Berlin>no</Berlin>
            <Munich>yes</Munich>
        </Germany>
        <France>
            <Paris>no</Paris>
        </France>
        <Italy>
            <Rome>no</Rome>
            <Venice>yes</Venice>
            <Milano>no</Milano>
        </Italy>
    </Europe>
    <Asia>
        <China>
            <Beijin>no</Beijin>
            <Shanghai>yes</Shanghai>
        </China>
        <India>
            <Mumbay>no</Mumbay>
        </India>
    </Asia>
    <America>
        <USA>
            <NewYork>
                <NewYork>no</NewYork>
                <Albany>yes</Albany>
            </NewYork>
            <California>
                <LosAngeles>no</LosAngeles>
                <SanFranciso>no</SanFranciso>                       
            </California>
        </USA>
        <Canada>
            <Vancouver>no</Vancouver>
            <Montreal>yes</Montreal>
        </Canada>
        <Mexico>
            <Tijuana>no</Tijuana>
        </Mexico>
    </America>
</world>

结果将是:

<?xml version="1.0" encoding="UTF-8"?>
<world>
   <Berlin>no</Berlin>
   <Munich>yes</Munich>
   <Paris>no</Paris>
   <Rome>no</Rome>
   <Venice>yes</Venice>
   <Milano>no</Milano>
   <Beijin>no</Beijin>
   <Shanghai>yes</Shanghai>
   <Mumbay>no</Mumbay>
   <NewYork>no</NewYork>
   <Albany>yes</Albany>
   <LosAngeles>no</LosAngeles>
   <SanFranciso>no</SanFranciso>
   <Vancouver>no</Vancouver>
   <Montreal>yes</Montreal>
   <Tijuana>no</Tijuana>
</world>