Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script to determine unused elements between XSLT and XML data source

Tags:

xml

xslt

Given a somefile.xslt which calls a datafile.xml, does a script exist that would output a report of node sections in the datafile.xml that are not being called by somefile.xslt?

Obviously a visual inspection of each file could be used as the basis for the analysis, but I'm looking for an automated method.

For example, my xslt contains xpath like:

<xsl:for-each select="//somenode/somesubnode/@attribute">

And the xml data source is expected to contain a somenode/somesubnode data structure. However, if it contains a someothernode data structure that's not a root element or child of an xpath called in the XSLT, it should be part of the "unused nodes" report.

like image 875
Scott B Avatar asked May 02 '26 08:05

Scott B


1 Answers

If you are using a push approach (xsl:apply-templates) instead of a pull approach (xsl:for-each) you can have a template with a negative priority that "catches" any elements that don't get matched by another template. It's more of an "unmatched" check than an "unused" check though.

Basic example...

XML Input

<doc>
    <foo>
        <bar>bar text</bar>
    </foo>
    <foo2>
        <bar>more bar text</bar>
    </foo2>
</doc>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="doc|foo|bar">
        <xsl:call-template name="ident"/>
    </xsl:template>

    <xsl:template match="*">
        <xsl:processing-instruction name="unused-element">
            <xsl:value-of select="name()"/>
        </xsl:processing-instruction>
        <xsl:call-template name="ident"/>
    </xsl:template>

</xsl:stylesheet>

XML Output

<doc>
   <foo>
      <bar>bar text</bar>
   </foo>
   <?unused-element foo2?><foo2>
      <bar>more bar text</bar>
   </foo2>
</doc>
like image 181
Daniel Haley Avatar answered May 04 '26 00:05

Daniel Haley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!