【发布时间】:2020-07-25 10:08:22
【问题描述】:
有一个包含许多兄弟<Line> 节点的文档,如下所示
<Report>
<Date>2020-07-25</Date>
<Number>12</Number>
<Line>
<LineNumber>1</LineNumber>
<Description>Some text</Description>
<Quantity>5</Quantity>
</Line>
<Line>
<LineNumber>2</LineNumber>
<Description>Some other text</Description>
<Quantity>9</Quantity>
</Line>
</Report>
我想得到一个输出,这样一个节点被组合成一个父节点
<INV>
<HEAD>
<DTM>2020-07-25</DTM>
<ID>12</ID>
</HEAD>
<LINES>
<LINE>
<NUM>1</NUM>
<DESC>Some text</DESC>
<QTY>5</QTY>
</LINE>
<LINE>
<NUM>2</NUM>
<DESC>Some other text</DESC>
<QTY>9</QTY>
</LINE>
</LINES>
</INV>
解决该问题的一种可能方法是按元素的名称对元素进行分组
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="3.0">
<xsl:mode streamable="yes" on-no-match="deep-skip"/>
<xsl:mode name="non-streamable" on-no-match="shallow-skip"/>
<xsl:template match="/Report">
<xsl:element name="INV">
<xsl:fork>
<xsl:for-each-group select="*" group-by="name() = 'Line'">
<xsl:choose>
<xsl:when test="current-grouping-key()">
<xsl:element name="LINES">
<xsl:apply-templates select="current-group()/copy-of()" mode="non-streamable"/>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:element name="HEAD">
<xsl:apply-templates select="current-group()/copy-of()" mode="non-streamable"/>
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:fork>
</xsl:element>
</xsl:template>
<xsl:template match="Date" mode="non-streamable">
<DTM>
<xsl:value-of select="."/>
</DTM>
</xsl:template>
<xsl:template match="Number" mode="non-streamable">
<ID>
<xsl:value-of select="."/>
</ID>
</xsl:template>
<xsl:template match="Line" mode="non-streamable">
<LINE>
<NUM>
<xsl:value-of select="LineNumber"/>
</NUM>
<DESC>
<xsl:value-of select="Description"/>
</DESC>
<QTY>
<xsl:value-of select="Quantity"/>
</QTY>
</LINE>
</xsl:template>
</xsl:stylesheet>
但是使用这种方法时,我面临着很高的内存消耗,它需要大约 2.5 GB 的 RAM 来转换一个包含大约 100 万行的现实生活中的 500 Mb 文档。这些分组的元素是否存储在内存中?我们可以避免吗?
还有其他方法可以执行此任务吗?
【问题讨论】: