【问题标题】:XSLT: Copying certain elements as children of another elementXSLT:将某些元素复制为另一个元素的子元素
【发布时间】:2018-12-02 15:25:48
【问题描述】:

我知道这种转变是微不足道的;但不幸的是我被困住了。 我的输入如下:

<?xml version="1.0" encoding="UTF-8"?>
<tests>
    <test>Biography</test>
    <test>Job</test>
    <test>Salary</test>
    <test>FirtsName</test>
    <test>John</test>
    <test>Mary</test>
    <test>David</test>
    <test>Isabella</test>
    <test>SecondName</test>
    <test>Jones</test>
    <test>Williams</test>
    <test>Biography</test>
    <test>Job</test>
    <test>Salary</test>
    <test>FirtsName</test>
    <test>Paul</test>
    <test>Peter</test>
    <test>SecondName</test>
    <test>Castro</test>
    <test>Ricci</test>
<tests>

我想要做的是,使用 xslt 2.0,选择元素“test”之间的所有元素,值为“FirstName”,元素“test”值为“SecondName”,并将它们复制为它们的子元素值“传记”的第一个前面的“测试”元素。 OUTPUT 应如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<tests>
    <test>Biography
        <test>John</test>
        <test>Mary</test>
        <test>David</test>
        <test>Isabella</test>
    </test>
    <test>Job</test>
    <test>Salary</test>
    <test>FirtsName</test>
    <test>SecondName</test>
    <test>Jones</test>
    <test>Williams</test>
    <test>Biography
        <test>Paul</test>
        <test>Peter</test>
    </test>
    <test>Job</test>
    <test>Salary</test>
    <test>FirtsName</test>
    <test>SecondName</test>
    <test>Castro</test>
    <test>Ricci</test>
</tests>

非常感谢您的帮助:)

【问题讨论】:

  • 那么你到底在哪里坚持这个? ——附言您的输入不是 XML - 您的输出也不是。你需要一个根元素。
  • 我基本上被困在我需要的 xpath 中。套用它,我需要在第一个 FirtsName 和第一个 SecondName 之间找到测试元素,并将它们移动到最近的前面 Biography 元素;然后,测试第二个 FirtsName 和第二个 SecondName 之间的元素,并将它们移动到最近的前面 Biography 元素等。它应该是一个组合我想的位置和xpath。
  • 你需要先分组,分组以Biography开头。然后在每个组中,您需要识别并在FirtsName 和SecondName 之间移动子组。为此,您需要使用 XPath &lt;&lt; 和 &gt;&gt; 运算符。
  • 非常感谢。解决方案非常简单。

标签: xml xslt copy element transformation


【解决方案1】:

看看这是否有帮助:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/tests">
    <xsl:copy>
        <xsl:for-each-group select="test" group-starting-with="test[.='Biography']">
            <xsl:variable name="names" select="current-group()[. >> current-group()[.='FirtsName'] and . &lt;&lt; current-group()[.='SecondName']]" />
            <test>
               <xsl:value-of select="current-group()[1]"/> 
               <xsl:text>&#10;</xsl:text>
               <xsl:copy-of select="$names"/>
            </test>
            <xsl:copy-of select="current-group()[position() gt 1] except $names" />
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

演示:https://xsltfiddle.liberty-development.net/94hvTAk

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多