如果XML中的子项为空,则替换父节点

问题描述 投票:0回答:1

文本XML标记中有一个tbody,可以在XML文档中的任何位置。如果tbody为空,我想要替换没有可用的数据

            <title>Payers</title>
                <text>
                    <table border="1" width="100%">
                        <thead>
                            <tr>
                                <th>Payer Name</th>
                                <th>Policy Type</th>
                                <th>Policy Number</th>
                                <th>Effective Date</th>
                                <th>Expiration Date</th>
                            </tr>
                        </thead>
                        <tbody />
                    </table>
                </text>

所以输出应该是

                <title>Payers</title>
                <text>
                    no data available
                </text>
xml xslt xslt-1.0
1个回答
0
投票

在节点text中使用验证,请参阅下面的XSL:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
  <xsl:strip-space elements="*"/>  
  <xsl:output method="xml" indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <!--perform validation in required node-->
    <xsl:template match="text">        
            <xsl:choose>
                <!--in case when tbody has some text then normally copy it-->
                <xsl:when test="string-length(normalize-space(//tbody/text())) &gt;0">
                        <xsl:copy-of select="."/>
                </xsl:when>
                <!--in case when tbody has not any text node text will have text - no data available-->
                <xsl:otherwise>
                    <xsl:element name="{name()}">
                        <xsl:text>&#xa;    no data available&#xa;</xsl:text>
                    </xsl:element>
                </xsl:otherwise>
            </xsl:choose>                                                                  
    </xsl:template>
</xsl:stylesheet>

所以如果XML如下:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <title>Payers</title>
        <text>
            <table border="1" width="100%">
                <thead>
                    <tr>
                        <th>Payer Name</th>
                        <th>Policy Type</th>
                        <th>Policy Number</th>
                        <th>Effective Date</th>
                        <th>Expiration Date</th>
                    </tr>
                </thead>
                <tbody/>
            </table>
        </text>
</root>

结果如下:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>Payers</title>
<text>
    no data available
</text>
</root>

希望它能帮到你的案子。

© www.soinside.com 2019 - 2024. All rights reserved.