【问题标题】:Inserting nodes from a XML to another XML file using xslt使用 xslt 将节点从 XML 插入到另一个 XML 文件
【发布时间】:2013-10-15 23:23:02
【问题描述】:

所以我有一个这样的 xml 文件:

<?xml version="1.0"?>
<class>

    <students>
        <name origin="English" firstname="Jeff" lastname="Richards"/>
        <name origin="French" firstname="Martel" lastname="Francois"/>
    </students>

    <teachers>
        <name origin="Spanish" firstname="Enrique" lastname="Rosa"/>
    </teachers>

</class>

还有另一个像这样的 xml 文件:

 <?xml version="1.0"?>
    <name origin="English" firstname="Richard" lastname="Priestly"/>
    <name origin="Russian" firstname="Alexey" lastname="Romanov"/>

使用 xslt,如何将第二个文件中的两个元素添加到第一个文件中的 student 元素中?换句话说,我怎样才能创建一个看起来像这样的文件:

<?xml version="1.0"?>
    <class>

        <students>
            <name origin="English" firstname="Jeff" lastname="Richards"/>
            <name origin="French" firstname="Martel" lastname="Francois"/>
            <name origin="English" firstname="Richard" lastname="Priestly"/>
            <name origin="Russian" firstname="Alexey" lastname="Romanov"/>
        </students>

        <teachers>
            <name origin="Spanish" firstname="Enrique" lastname="Rosa"/>
        </teachers>

    </class>

如果不能使用 xslt,是否可以使用 XPath?

非常感谢!

【问题讨论】:

  • 检查此stackoverflow.com/questions/15194718/… 并且您的 XML 示例无效。第二个没有根节点,最后一个你错过了&lt;class&gt;标签
  • 您的第二个文档不是 XML 文件。解决此问题后,您可以使用 document() 函数解析和处理第二个文件,并将其内容作为第一个 XML 文件转换的一部分。

标签: xml xslt xpath xslt-2.0


【解决方案1】:

这是一种方法,假设您通过添加“students”根节点并将其命名为“students.xml”来使第二个文件格式正确:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output indent="yes" method="xml"/>

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

<xsl:template match="students">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:for-each select="document('students.xml')/students/name">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 我试过这个并且得到以下错误--错误:处理指令目标匹配“[xX][mM][lL]”是不允许的。'
  • 没关系。这是因为我的一个文件在 xml 标头开始之前有一个空格。谢谢!!
  • 有什么方法可以复制它以使其正确缩进。使用上面的方法,名称元素一直向左移动。我希望它们缩进。
  • 您缺少 xsl:stylesheet 结束标记。
  • @4thex 对此感到抱歉。结束标签在那里,但它被代码格式隐藏了。现已修复。
猜你喜欢
  • 1970-01-01
  • 2013-03-26
  • 2012-08-16
  • 2013-02-22
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-22
相关资源
最近更新 更多