【问题标题】:Adding element in middle of xml using xslt使用 xslt 在 xml 中间添加元素
【发布时间】:2016-09-07 01:34:38
【问题描述】:

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

【问题讨论】:

    标签: xslt


    【解决方案1】:

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

    显然,逻辑会有所不同,具体取决于您从哪里获取新数据以及需要去哪里。上面的样式表只是在每个&lt;Name&gt; 元素之后插入一个&lt;Age&gt; 元素,在每个&lt;Dept&gt; 元素之后插入一个&lt;Domain&gt; 元素。

    (限制:如果您的文档可以在其他 &lt;Name&gt;&lt;Dept&gt; 元素中包含 &lt;Name&gt;&lt;Dept&gt; 元素,则只有最外面的元素会进行此特殊处理。我认为您不打算为您的文档有这种递归结构,所以它不会影响你,但值得一提以防万一。)

    【讨论】:

    • 如果您只希望元素添加一次,而不是为每个 Name/Dept 元素添加一次呢?
    • @Joe:哇,差不多 5 年后了。 :-) 在这种情况下,您将结果元素添加到仅匹配一次的模板中。例如。 match="/*/Name[1]".
    • 太好了,我真的没想到5年后会有答案,更不用说这么快了!这很有帮助
    • 如果我想将年龄(34)作为参数传递怎么办?我不想在 xslt 文件中硬编码 34。
    • @GLP:这取决于你想从哪里传递它。我建议创建一个新问题。
    【解决方案2】:

    我在现有样式表中修改了一些东西,它将允许您选择特定元素并在您的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多