问题描述
|
这是我的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>
而是产生相同的效果。
谢谢有帮助的人!
解决方法
似乎您想将输出文档中的所有元素放入\“ 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
在正确的命名空间中创建元素。,在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>