如何使用XSLT向XML添加顶级元素?

4

我有一个简单的XML文档,想要添加一个新的根元素。当前的根元素是<myFields>,我想要添加一个<myTable>元素,使其看起来像这样。

<myTable>
    <myFields>
    .
    .
    </myFields>
</myTable>

好问题,+1。请查看我的答案,这可能是最短的解决方案。 :) 它也是正确的! - Dimitre Novatchev
4个回答

6

类似下面这样的内容应该适合您:

<xsl:template match="/">
  <myTable>
    <xsl:apply-templates/>
  </myTable>
</xsl:template>

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

几乎可以工作,但不再有任何子元素,只有值。 - Marsharks
@Marsharks 和 @Ryan Berger:请注意,当根元素之前有一些 PI 时,此输出会产生奇怪的结果... - user357812
是的,我看到了。我的表单是 InfoPath 表单。我的解决方案对我有效。 - Marsharks

1

这可能是最短的解决方案 :)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
        <myTable> 
            <xsl:copy-of select="node()" /> 
        </myTable> 
    </xsl:template> 
</xsl:stylesheet>

1

这个样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/*">
        <myTable>
            <xsl:call-template name="identity"/>
        </myTable>
    </xsl:template>
    <xsl:template match="@*|node()" name="identity">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

注意:复制所有内容(包括根元素之前的PIs),并在根元素之前添加myTable


0

你帮我接近了目标

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:element name="myTable">
            <xsl:copy-of select="*" />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

如果您想保留文档元素之前的任何注释或处理指令,则@Ryan Berger的解决方案是正确的选择。 - Mads Hansen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接