Copying node attribute to a new node in xslt

2019-09-12 10: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?

3条回答
放我归山
2楼-- · 2019-09-12 10:43

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楼-- · 2019-09-12 10:45

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.

查看更多
Anthone
4楼-- · 2019-09-12 10:47

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>

查看更多
登录 后发表回答