Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

xml - XSLT Removing duplicates

I have an xml datasource which looks like this:

<dsQueryResponse>
  <Department>
    <Rows>
      <Row dept="HR" state="NY" region="East"/>
      <Row dept="HR" state="NJ" region="East"/>
      <Row dept="SD" state="NY" region="East"/>
      <Row dept="MM" state="NY" region="East"/>
      <Row dept="SD" state="NJ" region="East"/>
      <Row dept="SD" state="CO" region="West"/>
      <Row dept="MM" state="CO" region="West"/>
    </Rows>
  </Department>
</dsQueryResponse>

My XSLT looks like this:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="html" indent="no"/>
  <xsl:decimal-format NaN=""/>
  <xsl:param name="DeptQS">East</xsl:param>
  <xsl:variable name="deptRows" select="/dsQueryResponse/Department/Rows/Row[@region = $DeptQS]"/>

  <xsl:template match="/">
    <xsl:if test="count($deptRows) &gt; 0">
      <xsl:call-template name="deptList"/>
    </xsl:if>
  </xsl:template>

  <xsl:template name="deptList">
    <xsl:for-each select="$deptRows">
      <!-- process unique depts--> 
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

I want to get all the departments in the region written out. The code I have now will write out duplicate departments. But how can I write out the department for the region only once?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You haven't shown your desired output. But in XSLT 2.0, you could do something like this:

<xsl:template match="Rows">
  <xsl:for-each-group select="Row" group-by="@region">
    <region name="{current-grouping-key()}">
      <xsl:for-each-group select="current-group()" group-by="@dept">
        <dept name="{current-grouping-key()}">
          <xsl:for-each select="current-group()">
            <state name="{@state}"/>
          </xsl:for-each>
        </dept>
      </xsl:for-each-group>
    </region>
  </xsl:for-each>
</xsl:template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...