Skip to main content
 首页 » 编程设计

xslt之使用xslt在xml中间添加元素

2024年11月24日13kevingrace

下面是实际的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 元素?
请给我 sample !

请您参考如下方法:

这是一个 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> 

显然,逻辑将根据您将从何处获取新数据以及它需要去哪里而有所不同。上面的样式表仅仅插入了一个 <Age>每个 <Name> 之后的元素元素和 <Domain>每个 <Dept> 之后的元素元素。

(限制:如果您的文档可以在其他 <Name><Dept> 元素中包含 <Name><Dept> 元素,则只有最外层的元素才会有这种特殊处理。我认为您不打算让您的文档有这个一种递归结构,所以它不会影响你,但为了以防万一,值得一提。)