使用xslt进行转换时删除xml命名空间

时间:2014-04-08 15:54:03

标签: xslt

我正在使用XSLT转换XML并在删除命名空间时面临问题。如果我删除xmlns它工作正常。 问题1.它不会从已转换的XML中删除命名空间 问题2.我没有实现转型中的其他模板。

我的输入XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Catalog xmlns="http://example.com">
    <Books>
        <book1>Wise1 Otherwise</book1>
        <book2>Great Expectations</book2>
    </Books>
    <library>
        <Name> Forsyth </Name>
        <city> Cumming </city>
    </library>

</Catalog>

预期结果

<?xml version="1.0" encoding="UTF-8"?>
<Import>
   <Books>
      <book1>Wise1 Otherwise</book1>
      <book2>Great Expectations</book2>
   </Books>
   <elab>
       <Name> Forsyth </Name>
       <city> Cumming </city>
    </elab>
 </Import>

XSL

<?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" indent="yes"/>

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

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

<xsl:template match="@xmlns">
<xsl:element name="{local-name()}" namespace="http://example.com">
    <xsl:apply-templates select="node() | @*"/>
</xsl:element>
</xsl:template>

<xsl:template match="library">
    <elab>
        <xsl:apply-templates />
    </elab>
</xsl:template>

<xsl:template match="Catalog">
    <Import>
        <xsl:apply-templates />
    </Import>
</xsl:template>     

</xsl:stylesheet>

1 个答案:

答案 0 :(得分:2)

我认为你缺少XSLT模板中的命名空间声明来匹配元素: 这是我的尝试:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://example.com">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space  elements="*"/>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

<xsl:template match="ns:library">
    <elab>
        <xsl:apply-templates />
    </elab>
</xsl:template>

<xsl:template match="ns:Catalog">
    <Import>
        <xsl:apply-templates />
    </Import>
</xsl:template> 
</xsl:stylesheet>