请求您的帮助以使用XSLT 2转换XML
我的输入XML如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<Workers>
<Worker>
<Batch_number>1234</Batch_number>
<Name>David</Name>
<Assignment>
<type>A</type>
<name>New York</name>
</Assignment>
</Worker>
<Worker>
<Batch_number>1234</Batch_number>
<Name>David</Name>
<Assignment>
<type>B</type>
<name>Boston</name>
</Assignment>
</Worker>
<Worker>
<Batch_number>1234</Batch_number>
<Name>David</Name>
<Assignment>
<type>C</type>
<name>Chicago</name>
</Assignment>
</Worker>
<Worker>
<Batch_number>78698</Batch_number>
<Name>Karen</Name>
<Assignment>
<type>C</type>
<name>Chicago</name>
</Assignment>
</Worker>
</Workers>
所需的输出如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<Worker>
<Batch_number>1234</Batch_number>
<Name>David</Name>
<Assignment>
<type>A</type>
<name>New York</name>
</Assignment>
<Assignment>
<type>B</type>
<name>Boston</name>
</Assignment>
<Assignment>
<type>C</type>
<name>Chicago</name>
</Assignment>
</Worker>
<Worker>
<Batch_number>78698</Batch_number>
<Name>Karen</Name>
<Assignment>
<type>C</type>
<name>Chicago</name>
</Assignment>
</Worker>
转换的条件是:
如果输入文件中存在具有相同<Worker>
的子节点<Batch_number>
,则应将同一Assignment
的所有<Batch_number>
节点归为一个Worker
子节点在<Batch_number>
和<Name>
之后
有人可以帮助我编写正确的代码来实现这一目标吗?
-谢谢 阿努普
答案 0 :(得分:1)
尽管所需的输出XML格式不正确,但是这里有一个XSLT-2.0解决方案可以满足您的特殊需求:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/Workers">
<xsl:for-each-group select="Worker" group-by="Batch_number">
<Worker>
<Batch_number><xsl:value-of select="current-grouping-key()" /></Batch_number>
<Name><xsl:value-of select="current()/Name" /></Name>
<xsl:copy-of select="current-group()/Assignment" />
</Worker>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
其输出为:
<?xml version="1.0" encoding="UTF-8"?>
<Worker>
<Batch_number>1234</Batch_number>
<Name>David</Name>
<Assignment>
<type>A</type>
<name>New York</name>
</Assignment>
<Assignment>
<type>B</type>
<name>Boston</name>
</Assignment>
<Assignment>
<type>C</type>
<name>Chicago</name>
</Assignment>
</Worker>
<Worker>
<Batch_number>78698</Batch_number>
<Name>Karen</Name>
<Assignment>
<type>C</type>
<name>Chicago</name>
</Assignment>
</Worker>