xsl合并相同的元素

时间:2013-11-20 08:45:32

标签: xslt merge elements xmltable

遇到大问题:

<root>
<div>
    <programm></programm>
    <systemes><p></p></systemes>
    <systemes><table>.1.</table></systemes>
    <systemes><table>.2.</table></systemes>
    <systemes><p></p></systemes>
    <requirements></requirements>
</div>
<div>
    <programm></programm>
    <systemes><table>.1.</table></systemes>
    <systemes><p></p></systemes>
    <requirements></requirements>
</div>
<div>
    <programm></programm>
    <systemes><table>.1.</table></systemes>
    <systemes><table>.2.</table></systemes>
    <systemes><p></p></systemes>
    <requirements></requirements>
</div>
</root>

我需要输出为:

<root>
<div>
    <programm></programm>
    <systemes><p></p><table>.1.</table><table>.2.</table><p></p></systemes>
    <requirements></requirements>
</div>
<div>
    <programm></programm>
    <systemes><table>.1.</table><p></p></systemes>
    <requirements></requirements>
</div>
<div>
    <programm></programm>
    <systemes><table>.1.</table><table>.2.</table><p></p></systemes>
    <requirements></requirements>
</div>
</root>

我希望有人可以帮我解决这个问题。我知道Muenchian方法但是没有让它正常工作。非常感谢你!

这是我到目前为止所尝试的:

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

<xsl:strip-space elements="*"/>

<xsl:key name="systemsKey" match="//systemes" use="name()"/>

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
</xsl:template>

<xsl:template match="systemes[generate-id()=generate-id(key('systemesKey', name())[1])]">
    <xsl:copy>
        <xsl:apply-templates select="@*|key('systemesKey', name())/node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="systemes[not(generate-id()=generate-id(key('systemesKey', name())[1]))]"/>

</xsl:stylesheet>

1 个答案:

答案 0 :(得分:0)

这会产生您描述的输出(除了systemes元素内的子顺序)。

<?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="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="root">
  <xsl:copy>
     <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="requirements|programm|p">
  <xsl:copy>
     <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

<xsl:template match="div">
  <xsl:copy>
     <xsl:element name="systemes">
        <xsl:for-each select="systemes">
           <xsl:apply-templates/>
        </xsl:for-each>
     </xsl:element>
     <xsl:apply-templates select="requirements|programm"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="table">
  <xsl:copy>
     <xsl:value-of select="."/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

根本不需要使用分组,Muenchian。如果你想达到的目标没有必要,我建议你不要使用像钥匙这样复杂的东西。

编辑:我使用的是XSLT 2.0,但其中没有任何内容在1.0中无法完成。

相关问题