Home > Mobile >  Allowlisting (a.k.a. Whitelisting) XML fields from huge XML with XSLT
Allowlisting (a.k.a. Whitelisting) XML fields from huge XML with XSLT

Time:05-06

I would like to empty all fields from a really huge XML except certain fields (in this example the fields surname and the city New York from the lower node).

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8" omit-xml-declaration="yes"/>
 <SomeName>
    <identifier>        
        <name>Peter</name>
        <surname>Smith</surname>
        <city>London</city>
    </identifier>
    <MainNode1>
        <SubNode1>
            <street>Main Street</street>
            <city>New York</city>
        </SubNode1>
    </MainNode1>
 </SomeName>
... 

It should look like this:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8" omit-xml-declaration="yes"/>
 <SomeName>
    <identifier>
       </name>
       <surname>Smith</surname>
       </city>
    </identifier>
    <MainNode1>
       <SubNode1>
          <street/>
          <city>New York</city>
       </SubNode1>
    </MainNode1>
 </SomeName>
...

I have managed to empty all fields with this:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8" omit-xml-declaration="yes"/>
    <xsl:template match="*">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="text()" />
</xsl:stylesheet>

Now i only need the info how to "unselect" or "whitelist" certain fields. Also some fields have the same name in different nodes, so i guess i need to specify the Xpath when whitelisting.

CodePudding user response:

Here is one way you could look at it:

XSLT 1.0

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

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

<!-- default behavior for leaf nodes (priority=0.5) -->
<xsl:template match="*[not(*)]">
    <xsl:copy/>
</xsl:template>
    
<!-- override for white-listed nodes -->
<xsl:template match="surname | SubNode1/city" priority="1">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
  • Related