如何摆脱XSLT输出中的xmlns =“”(无命名空间)属性

时间:2011-04-20 04:59:58

标签: xml xslt

这是我的(本案例场景简化)XML:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="test_1.xsl" type="text/xsl"?>

<doc xmlns="http://www.foo.org">
  <div>
    <title>Mr. Title</title>
    <paragraph>This is one paragraph.
    </paragraph>
    <paragraph>Another paragraph.
    </paragraph>
  </div>
</doc>

这是我的XSLT:

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

<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

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

 <xsl:template match="foo:doc">
  <xsl:element name="newdoc" namespace="http://www/w3.org/1999/xhtml">
   <xsl:apply-templates/>
  </xsl:element>
 </xsl:template>

 <xsl:template match="foo:div">
  <segment title="{foo:title}">
   <xsl:apply-templates/>
  </segment>
 </xsl:template>

 <xsl:template match="foo:title">
  <xsl:element name="h2">
   <xsl:apply-templates/>
  </xsl:element>
 </xsl:template>

 <xsl:template match="foo:paragraph">
  <xsl:element name="p">
   <xsl:apply-templates/>
  </xsl:element>
 </xsl:template>

</xsl:stylesheet>

输出产生:

<newdoc xmlns="http://www/w3.org/1999/xhtml">
  <segment xmlns="" title="Mr. Title">
    <h2>Mr. Title</h2>
    <p>This is one paragraph.
    </p>
    <p>Another paragraph.
    </p>
  </segment>
</newdoc>

这是很好的,除了segment元素中的xmlns =“”之外,似乎没有为自己及其所有子节点定义命名空间。我怎么能让它不添加呢?

旁注:我也尝试用

转换第一个节点
<xsl:template match="mydoc:doc">
  <html xmlns="http://www/w3.org/1999/xhtml">
   <xsl:apply-templates/>
  </html>
 </xsl:template>
相反,它会产生相同的效果。

谢谢有帮助的人!

2 个答案:

答案 0 :(得分:11)

您似乎希望将输出文档中的所有元素放入“http://www/w3.org/1999/xhtml”命名空间。目前,您只为“newdoc”元素指定名称空间,所有其他元素都在默认名称空间中,因为样式表中没有名称空间声明。样式表中的嵌套确定元素属于哪个名称空间,而不是变换后的嵌套。

您可以在样式表中声明默认命名空间,以影响所有其他不合格的元素:

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

现在您不再需要xsl:element标记,可以直接使用newdoc在正确的命名空间中创建元素。

答案 1 :(得分:4)

foo:div模板中,使用空命名空间创建segment元素。由于父元素具有不同的命名空间,因此处理器必须添加此命名空间声明。

如果您想要的是segment,其命名空间与父级相同,请改用xsl:element

<xsl:template match="foo:div">
    <xsl:element name="segment">
        <xsl:attribute name="title">
            <xsl:value-of select="foo:title"/>
        </xsl:attribute>
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>
相关问题