这是我的(本案例场景简化)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>
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
输出产生这个:
<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>
Run Code Online (Sandbox Code Playgroud)
除了段元素中的xmlns =""之外,这很好,似乎没有为自己及其所有子节点定义名称空间.怎么能让它不添加呢?
旁注:我也试过改造第一个节点
<xsl:template match="mydoc:doc">
<html xmlns="http://www/w3.org/1999/xhtml">
<xsl:apply-templates/>
</html>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
相反,但它产生相同的效果.
谢谢有帮助的人!
Jör*_*ann 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">
Run Code Online (Sandbox Code Playgroud)
现在您也不再需要xsl:element标记,可以直接用于newdoc在正确的命名空间中创建元素.