首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用xslt在xml中间添加元素

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

Stack Overflow用户
提问于 2010-09-06 13:23:44
回答 2查看 58.2K关注 0票数 28

下面是实际的xml:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<employee>
 <Name>ABC</Name>
 <Dept>CS</Dept>
 <Designation>sse</Designation>
</employee>

我想要的输出如下:

代码语言:javascript
复制
<?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元素?请给我样品!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-09-06 14:45:40

下面是一个XSLT 1.0样式表,它将执行您所要求的操作:

代码语言:javascript
复制
<?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>元素,则只有最外层的元素才会进行这种特殊处理。我不认为您打算让您的文档具有这种递归结构,因此它不会影响您,但为了以防万一,它值得一提。)

票数 46
EN

Stack Overflow用户

发布于 2016-09-07 01:34:39

我已经在现有的样式表中修改了一些东西,它将允许您选择特定的元素并在xml中更新。

代码语言:javascript
复制
<?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:

代码语言:javascript
复制
<?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>
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3649195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档