Copying node attribute to a new node in xslt

怎甘沉沦 提交于 2019-12-25 07:55:20

问题


I have the xml like this:

<definitions xmlns:xxx="test.com" xmlns:yyy="test2.com" test="test">
</definitions>

which I need to convert like this:

<test xmlns:xxx="test.com" xmlns:yyy="test2.com" test="test">
</test>

I wrote an xslt like this:

<xsl:template match="definitions">
    <xsl:element name="test">
        <xsl:copy-of select="@*" />
    </xsl:element>
</xsl:template>

this produces:

<test test="test">
</test>

but it doesnt contain xmlns:xxx="test.com" xmlns:yyy="test2.com" namespaces why?

How can I copy along with namespaces also?


回答1:


it doesnt contain xmlns:xxx="test.com" xmlns:yyy="test2.com" namespaces why?

It doesn't contain the namespace declarations because they are not used anywhere - so the XSLT processor does not output them.

How can I copy along with namespaces also?

I don't see why you would want them - but if you insist, you could copy them explicitly:

<xsl:template match="definitions">
    <test>
        <xsl:copy-of select="@* | namespace::*" />
    </test>
</xsl:template>

Note that that it's not necessary to use xsl:element when the name of the element is known.




回答2:


The namespaces have to be declared in your XSL file, too:

<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xxx="test.com"
    xmlns:yyy="test2.com">



回答3:


It seems like that you just want to rename the element "definitions" to "test". You can use something like this.

<xsl:template match="definitions">
<test>
    <xsl:apply-templates select="@*" />
</test>



来源:https://stackoverflow.com/questions/36739044/copying-node-attribute-to-a-new-node-in-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!