How to change a whole element with an already existing value with xslt?
I have some original file with a header I want to change for another one (stored i other file):
original file:
<doc1>
<header>
<a>aaaa</a>
<b>bbbb</b>
</header>
<content>
<z>zzzzzzzzzzzzz</z>
</content>
</doc1>
new header (in a file):
<header>
<c>cccc</c>
</header>
expected result:
<doc1>
<header>
<c>cccc</c>
</header>
开发者_高级运维<content>
<z>zzzzzzzzzzzzz</z>
</content>
</doc1>
Thanks in advance!
This transformation (for demo-only purposes the new header is imbedded in the XSLT stylesheet):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my">
<xsl:output omit-xml-declaration="yes"/>
<my:header>
<header>
<c>cccc</c>
</header>
</my:header>
<xsl:variable name="vHeaderDoc" select="document('')/*/my:header"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="header">
<xsl:copy-of select="$vHeaderDoc/*"/>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<doc1>
<header>
<a>aaaa</a>
<b>bbbb</b>
</header>
<content>
<z>zzzzzzzzzzzzz</z>
</content>
</doc1>
produces the wanted, correct result:
<doc1>
<header xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
<c>cccc</c>
</header>
<content>
<z>zzzzzzzzzzzzz</z>
</content>
</doc1>
In the real case you will have:
<xsl:variable name="vHeaderDoc" select="document('Header.xml')"/>
and the header
document will be in the file named 'Header.xml'
that resides in the same directory as the XSLT stylesheet (if in another directory, then change the document URL accordingly).
In the real case, no xsl:
namespace node will be copied on the header
element.
Do note: The use of the standard XSLT function document()
.
If you want to use an external document then you need to use the xslt document function.
e.g./
http://www.ibm.com/developerworks/xml/library/x-tipcombxslt/ http://www.xml.com/pub/a/2002/03/06/xslt.html
精彩评论