Home > Software engineering >  XSLT Normalize namespace prefixes in an unknown context
XSLT Normalize namespace prefixes in an unknown context

Time:08-10

I'm attempting to build an XSLT (1.0) that works on an xml body which always contains the same namespaces but the prefixes for these namespaces are completely unknown and variable. The problem I'm having is that this causes 'undeclared prefix' errors when my application applies the stylesheet to the source xml. What's the best strategy to deal with this? If I know the namespace URIs can I simply reassign all prefix usages to a predefined prefix that I associate with that namespace in the XSLT? What would this look like?

Just as an example: source xml

<unknownPrefix:root 
  xmlns:unknownPrefix="knownURI"
  xmlns:unknownPrefix2="knownURI2"
  xmlns:unknownPrefix3="knownURI3"
>
  <unknownPrefix2:node unknownPrefix3:someattribute="example">text</unknownprefix2:node>
</unknownPrefix:root>

CodePudding user response:

Consider the following example:

XML

<unknownPrefix:root xmlns:unknownPrefix="knownURI" xmlns:unknownPrefix2="knownURI2" xmlns:unknownPrefix3="knownURI3">
    <unknownPrefix2:node unknownPrefix3:someattribute="example">text</unknownPrefix2:node>
</unknownPrefix:root>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:myPrefix1="knownURI" 
xmlns:myPrefix2="knownURI2" 
xmlns:myPrefix3="knownURI3"
exclude-result-prefixes="myPrefix1 myPrefix2 myPrefix3">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <result>
        <xsl:value-of select="myPrefix1:root/myPrefix2:node/@myPrefix3:someattribute"/>
    </result>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<result>example</result>
  • Related