使用xslt在xml中间添加元素 [英] Adding element in middle of xml using xslt
问题描述
下面是实际的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 元素?请给我样品!
Is this possible to add XML element in between using xslt? Please give me sample!
推荐答案
这是一个 XSLT 1.0 样式表,可以满足您的要求:
Here is an XSLT 1.0 stylesheet that will do what you asked:
<?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>
显然,逻辑会有所不同,具体取决于您将从何处获取新数据以及它需要去往何处.上面的样式表只是在每个
元素之后插入一个
元素,并在每个
元素之后插入一个
元素code>
Obviously the logic will vary depending on where you will be getting the new data from, and where it needs to go. The above stylesheet merely inserts an <Age>
element after every <Name>
element, and a <Domain>
element after every <Dept>
element.
(限制:如果您的文档可以在其他
或
或
元素中包含
code><Dept> 元素,只有最外层的才会有这种特殊的处理.我认为你不打算让你的文档有这种递归结构,所以它不会影响你,但它是值得一提,以防万一.)
(Limitation: if your document could have <Name>
or <Dept>
elements within other <Name>
or <Dept>
elements, only the outermost ones will have this special processing. I don't think you intend for your document to have this kind of recursive structure, so it wouldn't affect you, but it's worth mentioning just in case.)
这篇关于使用xslt在xml中间添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!