簡體   English   中英

XSLT-檢查子節點是否有價值

[英]XSLT-Check if child node has value

我以以下格式大致輸入了xml。

<Root>
       <PAF>
         <Child1 xsi:nil="true" />
         <Child2 xsi:nil="true" />
         <Child3>BlahBlah</Child3>
       </PAF>
   </Root>

在將其轉換為XML的同時,我想檢查<PAF>是否具有任何有價值的子對象(在我的情況下為<Child3> ),然后執行一些操作。 如果所有孩子都為nil =“ true”,則執行某項操作

對於XSLT腳本,我有點陌生,到目前為止,我只能獲得<PAF>的子節點數。 有人可以在我的上下文中建議我if-else語法嗎? 我這里需要任何XPATH表達式嗎?

謝謝你的時間。

您需要執行以下代碼:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:xsi="www.nill.com"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="1.0">

    <xsl:output method="xml" indent="yes"/>

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

    <xsl:template match="PAF">
        <xsl:choose>
            <!--Checked no data inside PAF and its descendants and not other attributes other than xsi:nill then Drop.--> 
            <xsl:when test="(count(descendant-or-self::*/@*[not(name() = 'xsi:nil')]) = 0) and (not(normalize-space()))"/>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates select="@* | node()"/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

假設您使用的是PAX ,則可以這樣:

<xsl:choose>
    <xsl:when test="*[not(@xsi:nil='true')]">
        <!-- not all chiLd nodes are empty -->
        <!-- DO SOMETHING HERE -->
    </xsl:when>
    <xsl:otherwise>
        <!-- all child nodes are empty -->
        <!-- DO SOMETHING ELSE -->
    </xsl:otherwise>
</xsl:choose>

如果沒有其他操作,請使用xsl:if而不是xsl:choose


請注意, xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"聲明必須同時存在於XML和XSLT文檔中。

暫無
暫無

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

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