I have an xml file :
<?xml version="1.0" encoding="iso-8859-1"?>
<Configuration>
<Parameter2>
</Parameter2>
</Configuration>
and I'd like to add following part to my xml file between <Configuration>
and <Parameter2>
parts.
<Parameter1>
<send>0</send>
开发者_开发知识库 <interval>0</interval>
<speed>200</speed>
</Parameter1>
This XSLT inserts the specified content as a child of the Configuration
element, before Parameter2
.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="yes" />
<xsl:template match="Configuration">
<xsl:copy>
<xsl:apply-templates select="@*" />
<!--Check for the presence of Parameter1 in the config file to ensure that it does not get re-inserted if this XSLT is executed against the output-->
<xsl:if test="not(Parameter1)">
<Parameter1>
<send>0</send>
<interval>0</interval>
<speed>200</speed>
</Parameter1>
</xsl:if>
<!--apply templates to children, which will copy forward Parameter2 (and Parameter1, if it already exists)-->
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:template>
<!--standard identity template, which copies all content forward-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Shorter solution. This stylesheet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()" name="identity">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="Configuration/*[1]">
<Parameter1>
<send>0</send>
<interval>0</interval>
<speed>200</speed>
</Parameter1>
<xsl:call-template name="identity" />
</xsl:template>
</xsl:stylesheet>
Output:
<Configuration>
<Parameter1>
<send>0</send>
<interval>0</interval>
<speed>200</speed>
</Parameter1>
<Parameter2></Parameter2>
</Configuration>
Note: If you want to add Parameter1
only if there isn't already such element in any position, you should change the pattern for: Configuration/*[1][not(/Configuration/Parameter1)]
精彩评论