1

给定以下 xml

   <Root>
 <Employee>
   <service>
     <Record>xxx</Record>
     <Record>yyy</Record>
   </service>
   <service>
    <Record>xxx</Record>
    <Record>yyy</Record>
    <Record>zzz</Record>
   </service>
</Employee>
<Employee>
  <service>
     <Record>xxx</Record>
     <Record>yyy</Record>
   </service>
   <service>
    <Record>xxx</Record>
    <Record>yyy</Record>
    <Record>zzz</Record>
   </service>
</Employee>
</Root>

使用 XSLT1.0,在为每个包含 'xxx'、'yyy'、'zzz'<Employee><Record>字段转换 xml 时,结果中应该只出现一次

<Root>
 <Employee>
    <Service>
     <Record>xxx</Record>
     <Record>yyy</Record>
     <Record>zzz</Record>
   </Service>
</Employee>
<Employee> 
  <Service>
  <Record>xxx</Record>
  <Record>yyy</Record>
  <Record>zzz</Record>
 <Service>
</Employee>
</Root>

在 Employee 的 for-each 循环中,我厌倦了使用<xsl:if test='not(preceding::./service/Record=$record)'>. 该测试适用于第一次<Employee>参加<Record>for 'xxx','yyy','zzz' 一次。当迭代进入下一个<Employee>时,测试条件也会检查第一个中的<Record>值,<Employee>它发现前面的节点已经存在值'xxx','yyy','zzz',因此我无法获取记录第二个<Employee>。如何获得<Record>第二个中的 s <Employee>。任何帮助深表感谢。

谢谢

4

1 回答 1

0

此转换使用 Muenchian 方法进行分组

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

 <xsl:key name="kEmpRecordByVal" match="Employee/service/Record"
  use="concat(generate-id(../..), '+', .)"/>

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

 <xsl:template match="Employee">
  <Employee>
    <xsl:apply-templates select=
     "service/Record
           [generate-id()
           =
            generate-id(key('kEmpRecordByVal',
                            concat(generate-id(../..), '+', .)
                            )[1]
                        )
           ]
     "/>
  </Employee>
 </xsl:template>
</xsl:stylesheet>

当应用于以下 XML 文档时(为第二个提供了不同的值Employee以提高可读性):

<Root>
    <Employee>
        <service>
            <Record>xxx</Record>
            <Record>yyy</Record>
        </service>
        <service>
            <Record>xxx</Record>
            <Record>yyy</Record>
            <Record>zzz</Record>
        </service>
    </Employee>
    <Employee>
        <service>
            <Record>aaa</Record>
            <Record>bbb</Record>
        </service>
        <service>
            <Record>aaa</Record>
            <Record>bbb</Record>
            <Record>ccc</Record>
        </service>
    </Employee>
</Root>

产生了想要的正确结果:

<Root>
   <Employee>
      <Record>xxx</Record>
      <Record>yyy</Record>
      <Record>zzz</Record>
   </Employee>
   <Employee>
      <Record>aaa</Record>
      <Record>bbb</Record>
      <Record>ccc</Record>
   </Employee>
</Root>
于 2012-04-27T12:56:53.023 回答