簡體   English   中英

通過整個節點集比較屬性值

[英]Compare attribute values through whole node-set

我有xml數據。 並使用xslt轉換對其進行解析。 我需要找出特定元素的所有子元素是否具有相同的嵌套元素值。 看:

如果我們在中具有相同的值:

<parent>
   <child>
      <compare>1</compare>
   </child>
   <child>
      <compare>1</compare>
   </child>
</parent>

我們應該復制所有樹並將標志設置為“ 1”:

<parent>
   ...
   </child>
   <flag>1</flag>
</parent>

如果我們有不同的值:

<parent>
   <child>
      <compare>1</compare>
   </child>
   <child>
      <compare>2</compare>
   </child>
</parent>

我們應該復制所有樹並將標志設置為“”:

<parent>
   ...
   </child>
   <flag/>
</parent>

如果比較與第一個有什么不同呢?

<xsl:template match="/parent">
  <parent>
    <xsl:copy-of select="*"/>
    <flag>
      <xsl:if test="not(child[1]/compare != child/compare)">1</xsl:if>
    </flag>
  </parent>
</xsl:template>

這確實意味着如果您只有一個,則其標志將為1

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output indent="yes"/>

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

    <xsl:template match="parent">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
            <flag>
                <xsl:variable name="comp" select="child[1]/compare"/>
                <!-- add flag value only if child/compare are the same -->
                <xsl:value-of select="child[1]/compare[
                    count(current()/child)
                    = 
                    count(current()/child[ compare=$comp ]
                    )]"/>
            </flag>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

此轉換

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

 <xsl:template match="/*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
       <flag><xsl:value-of select=
       "substring('1', 2 - not(child[compare != current()/child/compare]))"/></flag>
     </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

當應用於以下XML文檔時:

<parent>
   <child>
      <compare>1</compare>
   </child>
   <child>
      <compare>1</compare>
   </child>
</parent>

產生想要的正確結果:

<parent>
   <child>
      <compare>1</compare>
   </child>
   <child>
      <compare>1</compare>
   </child>
   <flag>1</flag>
</parent>

在此XML文檔上應用相同的轉換時:

<parent>
   <child>
      <compare>1</compare>
   </child>
   <child>
      <compare>2</compare>
   </child>
</parent>

再次產生想要的正確結果:

<parent>
   <child>
      <compare>1</compare>
   </child>
   <child>
      <compare>2</compare>
   </child>
   <flag/>
</parent>

注意事項

  1. 使用並覆蓋身份規則。

  2. 根本不使用任何明確的條件指令(或變量)。

暫無
暫無

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

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