使用xslt在xml中间添加元素

Mad*_* CM 25 xslt

下面是实际的xml:

<?xml version="1.0" encoding="utf-8"?>
<employee>
 <Name>ABC</Name>
 <Dept>CS</Dept>
 <Designation>sse</Designation>
</employee>
Run Code Online (Sandbox Code Playgroud)

我想要输出如下:

<?xml version="1.0" encoding="utf-8"?>
<employee>
 <Name>ABC</Name>
  <Age>34</Age>
 <Dept>CS</Dept>
  <Domain>Insurance</Domain>
 <Designation>sse</Designation>
</employee>
Run Code Online (Sandbox Code Playgroud)

是否可以使用xslt在两者之间添加XML元素?请给我样品!

Lar*_*rsH 37

这是一个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>
Run Code Online (Sandbox Code Playgroud)

显然,逻辑将根据您从哪里获取新数据以及需要去哪里而变化.上述样式表仅仅插入一个<Age>每后元件<Name>元件和<Domain>每个后元件<Dept>元件.

(限制:如果您的文档可能有<Name><Dept>内其他元素<Name><Dept>.元素,只有最外面都会有这种特殊的处理,我不认为你打算为您的文档有这种递归结构的,所以它不会影响你,但值得一提的是以防万一.)


sat*_*hya 5

我在现有样式表中修改了一些内容,它将允许您选择特定元素并在 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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)