从输出xml中删除空的xmlns命名空间

7
我有一个输入的XML文件,在我的XSL中我调用了一个模板。模板内第一个标签显示为空的xmlns属性,如下所示:
    <Section xmlns="">

这个属性能在XSLT中被消除吗?

请帮我解决这个问题。

我只是添加了一个代码示例,

Input.xml:

<?xml version="1.0" encoding="utf-8"?>
<List>
<Sections>
<Section>
<Column>a</Column>
<Column>b</Column>
<Column>c</Column>
<Column>d</Column>
<Column>e</Column>
</Section>
</Sections>
</List>

Stylesheet.xsl

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

<xsl:template match="List">
    <report xmlns="http://developer.com/">      
        <Views>             
            <xsl:call-template name="Page"/>                
        </Views>        
    </report>   
</xsl:template> 

<xsl:template name="Page">
    <Content>
        <xsl:for-each select="./Sections/Section">
            <Columns>
            <xsl:for-each select="./Column">
                <Column>
                    <xsl:attribute name="value">
                        <xsl:value-of select="."/>
                    </xsl:attribute>
                </Column>
            </xsl:for-each> 
            </Columns>
        </xsl:for-each>
    </Content>
</xsl:template>

输出的output.xml文件长这样:
<?xml version="1.0" encoding="UTF-8"?>
<report xmlns="http://developer.com/">
<Views>
    <Content xmlns="">
        <Columns>
            <Column value="a"/>
            <Column value="b"/>
            <Column value="c"/>
            <Column value="d"/>
            <Column value="e"/>
        </Columns>
    </Content>
</Views>

我需要在<report>标签中添加xmlns属性,但不需要在<Content>标签中添加。这个xmlns属性是因为我调用了一个模板,该模板的第一个标签带有此属性。


请提供足够的代码(XML,XSLT),以便我们能够重现您的问题。 - michael.hor257k
1
xmlns="" 不是一个属性,而是一个命名空间声明。它们看起来相同,但具有不同的目的,您不能简单地添加或删除 xmlns "属性",而是要确保首先在正确的命名空间中创建元素,序列化程序将负责插入必要的命名空间声明,以使输出 XML 反映您创建的节点树。 - Ian Roberts
2个回答

8
在你的XSLT中给Content添加命名空间:
<xsl:template name="Page">
    <Content xmlns="http://developer.com/">

5
您需要将您的第二个模板更改为:

<xsl:template name="Page">
    <Content xmlns="http://developer.com/">
        <xsl:for-each select="./Sections/Section">
            <Columns>
            <xsl:for-each select="./Column">
                <Column>
                    <xsl:attribute name="value">
                        <xsl:value-of select="."/>
                    </xsl:attribute>
                </Column>
            </xsl:for-each> 
            </Columns>
        </xsl:for-each>
    </Content>
</xsl:template>

否则,您将会把<Content>元素及其所有子元素放置在无命名空间中 - 结果文档必须反映这一点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接