Home > Mobile >  Check if XML document is empty (that the root has no child nodes) using XSLT
Check if XML document is empty (that the root has no child nodes) using XSLT

Time:05-10

I have a XML document. In this case, it is empty:

<Converting/>

I want to throw an exception if the XML document is empty, and I am using XSLT-1.0. I imagine something like

<xsl:template match="root[not(*)]"/>

However, this does not seem to work out for me. Any ideas?

Kind regards

edit: I want to create this inside a template, so I cannot use a template

CodePudding user response:

Write a template what match the root element and then within this template count child node. If count is 0, write a text into output or throw an exception.

Approach 1

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="/*">
        <xsl:if test="count(./*) = 0">
            <xsl:text>doc is empty</xsl:text>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Approach 2

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="/*">
        <xsl:if test="count(./*) = 0">
            <xsl:message terminate="yes">doc is empty</xsl:message>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
  • Related