我需要合并两个节点 street ,因为它们具有相同的内容:
必须合并属性值(请参阅本文末尾的输出文件)
这是输入文件:
<country>
<state id="NEW JERSEY">
<city id="NEW YORK">
<district id="BRONX" method="modify">
<street id="0" method="modify">
<attributes>
<temperature>98</temperature>
<altitude>1300</altitude>
</attributes>
</street>
<dadada id="99" method="modify" />
<street id="0" method="modify">
<attributes>
<temperature>80</temperature>
<streetnumber> 67 </streetnumber>
</attributes>
</street>
<dididi id="432" method="modify" />
</district>
</city>
</state>
预期产出:
<country>
<state id="NEW JERSEY">
<city id="NEW YORK">
<district id="BRONX" method="modify">
<street id="0" method="modify">
<attributes>
<temperature>80</temperature>
<altitude>1300</altitude>
<streetnumber> 67 </streetnumber>
</attributes>
</street>
<dadada id="99" method="modify" />
<dididi id="432" method="modify" />
</district>
</city>
</state>
</country>
请帮助,我刚刚开始XSLT
答案 0 :(得分:1)
我假设您对XSLT 2.0感兴趣,因为这是您标记问题的方式。如果您需要XSLT 1.0等效,请告诉我。这个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:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[street]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:for-each-group select="street" group-by="@method">
<xsl:apply-templates select="current-group()[1]" />
</xsl:for-each-group>
<xsl:apply-templates select="node()[not(self::street)]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="street/attributes">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:variable name="grouped-method" select="../@method" />
<xsl:for-each-group select="../../street[@method=$grouped-method]/attributes/*" group-by="name()">
<xsl:apply-templates select="current-group()[1]" />
</xsl:for-each-group>
<xsl:apply-templates select="comment()|processing-instruction()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
第二个模板,匹配作为街道父母的元素,将通过常用方法对子街道进行分组。对于每个组,仅复制组中的第一条街道。其余的都被丢弃了。
当该组的第一条街道在第三个模板中具有其“属性”节点进程时,我们合并来自同一组的所有属性。可能'属性'是XML文档中不幸的元素名称!通过查看具有相同街道父(布朗克斯区)并按元素名称分组的所有联盟街道的所有“属性”子节点来实现此分组。如果这样的组中有多个元素,只需从第一个元素中获取值。
我不确定这正是你想要的,因为虽然街道属性是由'父'节点(布朗克斯)合并的,但它们并没有在城市层面合并。这反映了您问题的模糊性。您样本日期中街道的“父亲”节点是区域而不是城市。如果我错了,你想要在城市一级进行分组,请澄清并更新你的问题。