簡體   English   中英

子節點的 XSLT 密鑰分組

[英]XSLT Key Grouping for Child Nodes

<root>
   <Entry>
      <ID>1</ID>
      <Details>
         <Code>A1</Code>
         <Value>1000</Value>
      </Details>

      <Details>
         <Code>A2</Code>
         <Value>2000</Value>
      </Details>
   </Entry>

   <Entry>
      <ID>2</ID>
      <Details>
         <Code>B1</Code>
         <Value>1500</Value>
      </Details>

      <Details>
         <Code>B2</Code>
         <Value>2500</Value>
      </Details>

      <Details>
         <Code>A3</Code>
         <Value>3000</Value>
      </Details>
   </Entry>

</root>

我有這個輸入 XML。 對於每個<Entry> ,我希望對<Details>節點(它們是 Entry 的子節點)進行分組,並最終通過以下代碼分組獲取<Value>節點值的總和如下:

  1. 代碼 A1、A2 和 A3 應組合在一起(例如“A”)
  2. 代碼 B1、B2 和 B3 應組合在一起(例如“B”)

[注意:代碼只是舉例,實際代碼完全不同,所以子字符串解決方案不起作用,請不要從字面上考慮這些代碼]

輸出看起來像:

<Output>
    <Output-Line>
       <ID> 1 </ID>
      <Code-group> A </Code-group>
      <Sum> 3000 </Sum>

      <Code-group> B </Code-group>
      <Sum/>
    </Output-Line>

   <Output-Line>
       <ID> 2 </ID>
      <Code-group> A </Code-group>
      <Sum> 3000 </Sum>

      <Code-group> B </Code-group>
      <Sum> 4000 </Sum>
    </Output-Line>
</Output>

我目前面臨的問題是<xsl:key>元素應該在 for-each 循環中的頂部聲明,而不是在單個 Entry 級別聲明。 因此,我無法使用匹配和使用表達式參數形成正確的鍵。 任何幫助表示贊賞。

提前致謝!

假設這只是您之前 question 的另一個變體,您需要做的就是向key()函數調用添加另一個參數,以將其限制為當前Entry

XSLT 2.0

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

<xsl:key name="entry" match="Details" use="Code"/>

<xsl:template match="/root">
    <Output>
        <xsl:for-each select="Entry">
            <Output-Line>
                <xsl:copy-of select="ID"/>
                <Code-group> A </Code-group>
                <Sum>
                    <xsl:value-of select="sum(key('entry', ('A1', 'A2', 'A3'), .)/Value)" />
                </Sum>
                <Code-group> B </Code-group>
                <Sum>
                    <xsl:value-of select="sum(key('entry', ('B1', 'B2', 'B3'), .)/Value)" />
                </Sum>
            </Output-Line>
        </xsl:for-each>
    </Output>
</xsl:template>

</xsl:stylesheet>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM