下面是实际的xml:
<?xml version="1.0" encoding="utf-8"?>
<employee>
<Name>ABC</Name>
<Dept>CS</Dept>
<Designation>sse</Designation>
</employee>
我想要的输出如下:
<?xml version="1.0" encoding="utf-8"?>
<employee>
<Name>ABC</Name>
<Age>34</Age>
<Dept>CS</Dept>
<Domain>Insurance</Domain>
<Designation>sse</Designation>
</employee>
是否可以使用xslt在两者之间添加XML元素?请给我样品!
发布于 2010-09-06 14:45:40
下面是一个XSLT 1.0样式表,它将执行您所要求的操作:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- Identity transform -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Name">
<xsl:copy-of select="."/>
<Age>34</Age>
</xsl:template>
<xsl:template match="Dept">
<xsl:copy-of select="."/>
<Domain>Insurance</Domain>
</xsl:template>
</xsl:stylesheet>
显然,根据您将从何处获取新数据以及需要将其发送到何处,逻辑会有所不同。上面的样式表只是在每个<Name>
元素之后插入一个<Age>
元素,在每个<Dept>
元素之后插入一个<Domain>
元素。
(限制:如果您的文档可以在其他<Name>
或<Dept>
元素中包含<Name>
或<Dept>
元素,则只有最外层的元素才会进行这种特殊处理。我不认为您打算让您的文档具有这种递归结构,因此它不会影响您,但为了以防万一,它值得一提。)
发布于 2016-09-07 01:34:39
我已经在现有的样式表中修改了一些东西,它将允许您选择特定的元素并在xml中更新。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- Identity transform -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Name[1]">
<xsl:copy-of select="."/>
<Age>34</Age>
</xsl:template>
<xsl:template match="Dept[1]">
<xsl:copy-of select="."/>
<Domain>Insurance</Domain>
</xsl:template>
</xsl:stylesheet>
XML:
<?xml version="1.0" encoding="utf-8"?>
<employee>
<Name>ABC</Name>
<Dept>CS</Dept>
<Designation>sse</Designation>
<Name>CDE</Name>
<Dept>CSE</Dept>
<Designation>sses</Designation>
</employee>
https://stackoverflow.com/questions/3649195
复制相似问题