Lachlan Ennis
Lachlan Ennis

Reputation: 1128

Ignore bad XMLNS tag in XSL

I have an xml file provided by a third party for which I cannot change the output.

XML is structured similar to the following:

<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="ReportName">
    <table>
        <details attribute1="value"/>
    </table>
</report>

Due to the invalid xmlns I can't parse the document properly.

My xslt is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8" indent="yes" />
<xsl:preserve-space elements="*" />
<!-- root template -->
<xsl:template match="/">
    <applications>
        <xsl:apply-templates select="Report/table/details"/>
    </applications>
</xsl:template> 
<!-- details template -->
<xsl:template match="details">
    <application>
        <name><xsl:value-of select="@attribute1"/></name>
    </application>
</xsl:template>  

Is there a way to ignore the bad xmlns in the xslt? or do I need to pre-process it to remove the bad value? Or is it just a setting in the parser? I'm using XslCompiledTransform in .Net to parse it.

Upvotes: 0

Views: 398

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117018

Namespaces are to be used, not ignored. Since your XML uses a default namespace, you need to declare it in your stylesheet, assign it a prefix, and use that prefix when addressing the elements in the source XML.

Once you have fixed the <Report> vs. </report> mismatch (XML is case-sensitive!), the following stylesheet should work for you:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="ReportName"
exclude-result-prefixes="ns1">
<xsl:output encoding="UTF-8" indent="yes" />

<!-- root template -->
<xsl:template match="/">
    <applications>
        <xsl:apply-templates select="ns1:Report/ns1:table/ns1:details"/>
    </applications>
</xsl:template> 

<!-- details template -->
<xsl:template match="ns1:details">
    <application>
        <name>
            <xsl:value-of select="@attribute1"/>
        </name>
    </application>
</xsl:template> 

</xsl:stylesheet>

Upvotes: 1

Related Questions