【问题标题】:group by xml document by child element按子元素按xml文档分组
【发布时间】:2020-01-28 15:07:44
【问题描述】:

我有以下 xml。它是一组记录父节点,包含标识符、数量和类别。

<Data>
<record>
    <identifier>1000</identifier>
    <category>B</category>
    <quantity>90.00</quantity>
</record>
<record>
    <identifier>1000</identifier>
    <category>B</category>
    <quantity>50.00</quantity>
</record>
<record>
    <identifier>1001</identifier>
    <category>B</category>
    <quantity>13.00</quantity>
</record>
<record>
    <identifier>1002</identifier>
    <category>B</category>
    <quantity>100.00</quantity>
</record>

我需要按子“标识符”按记录元素分组。 预期的输出是这样的。

<Data>
<records>
    <record>
        <identifier>1000</identifier>
        <category>B</category>
        <quantity>90.00</quantity>
    </record>
    <record>
        <identifier>1000</identifier>
        <category>B</category>
        <quantity>50.00</quantity>
    </record>
</records>
<records>
    <record>
        <identifier>1001</identifier>
        <category>B</category>
        <quantity>13.00</quantity>
    </record>
</records>
<records>
    <record>
        <identifier>1002</identifier>
        <category>B</category>
        <quantity>100.00</quantity>
    </record>
</records>

我正在使用这个 xslt,但它在分组级别上都不起作用。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" encoding="UTF-8" omit-xml-declaration="yes" />
<xsl:template match="Data">
    <Data>
        <xsl:for-each-group select="record" group-by="identifier">
            <records>
                <xsl:for-each select="current-group()">
                    <xsl:copy>
                        <xsl:value-of select="*" />
                    </xsl:copy>
                </xsl:for-each>
            </records>
        </xsl:for-each-group>
    </Data>
</xsl:template>

如何修复它以使其正常工作?

【问题讨论】:

  • 我尝试更改 xslt-2.0 但执行时出错。
  • @JamesTaylor 错误信息是什么?
  • 无法使用提供的 XML/XSL 输入生成 XML 文档。 org.xml.sax.SAXParseException;行号:1;列号:20;不支持 XML 版本“2.0”,仅支持 XML 1.0
  • 您已将“2.0”版本放入 XML 声明中。喜欢&lt;?xml version="2.0" encoding="UTF-8"?&gt;。不要。
  • 它不起作用..

标签: xml xslt xslt-2.0 xslt-grouping


【解决方案1】:

您可以通过稍微调整(和简化)您的样式表来实现您展示的结果:

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" indent="yes" encoding="UTF-8" omit-xml-declaration="yes" />
<xsl:strip-space elements="*"/>

<xsl:template match="/Data">
    <Data>
        <xsl:for-each-group select="record" group-by="identifier">
            <records>
                <xsl:copy-of select="current-group()" />
            </records>
        </xsl:for-each-group>
    </Data>
</xsl:template>

</xsl:stylesheet>

演示:https://xsltfiddle.liberty-development.net/ncnu9B8/1

【讨论】:

  • 第 8 行有一个错字(记录/记录 -> 记录)。修复后,它可以工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
相关资源
最近更新 更多