xml 为元素添加命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/144713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a namespace to elements
提问by Craig Walker
I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this?
我有一个包含未命名空间元素的 XML 文档,我想使用 XSLT 向它们添加命名空间。大多数元素将在命名空间 A 中;一些将在命名空间 B 中。我该怎么做?
回答by andrewdotn
With foo.xml
使用 foo.xml
<foo x="1">
<bar y="2">
<baz z="3"/>
</bar>
<a-special-element n="8"/>
</foo>
and foo.xsl
和 foo.xsl
<xsl:template match="*">
<xsl:element name="{local-name()}" namespace="A" >
<xsl:copy-of select="attribute::*"/>
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="a-special-element">
<B:a-special-element xmlns:B="B">
<xsl:apply-templates match="children()"/>
</B:a-special-element>
</xsl:template>
</xsl:transform>
I get
我得到
<foo xmlns="A" x="1">
<bar y="2">
<baz z="3"/>
</bar>
<B:a-special-element xmlns:B="B"/>
</foo>
Is that what you're looking for?
这就是你要找的吗?
回答by ddaa
You will need two main ingredients for this recipe.
这个食谱需要两种主要成分。
The sauce stock will be the identity transform, and the main flavor will be given by the namespaceattribute to xsl:element.
酱汁将是身份转换,主要风味将由namespace属性 to赋予xsl:element。
The following, untested code, should add the http://example.com/namespace to all elements.
以下未经测试的代码应将http://example.com/命名空间添加到所有元素。
<xsl:template match="*">
<xsl:element name="xmpl:{local-name()}" namespace="http://example.com/">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
Personal message: Hello, Jeni Tennison. I know you are reading this.
个人信息:你好,Jeni Tennison。我知道你在读这个。
回答by Craig Walker
Here's what I have so far:
这是我到目前为止所拥有的:
<xsl:template match="*">
<xsl:element name="{local-name()}" namespace="A" >
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="a-special-element">
<B:a-special-element xmlns:B="B">
<xsl:apply-templates />
</B:a-special-element>
</xsl:template>
This almost works; the problem is that it's not copying attributes. From what I've read thusfar, xsl:element doesn't have a way to copy all of the attributes from the element as-is (use-attribute-sets doesn't appear to cut it).
这几乎有效;问题是它没有复制属性。从我迄今为止所读到的内容来看, xsl:element 无法按原样复制元素中的所有属性(use-attribute-sets 似乎没有削减它)。

