Skip to content Skip to sidebar Skip to footer

Remove All Namespaces From Xml

Is there a way to remove namespaces from an xml (where I know there aren't any name collisions)? Currently I'm doing this for each known namespace: s = re.sub(r'(<\/?)md:', r'\1

Solution 1:

You can use the XSLT approach by calling the following XSLT-1.0 template from Python. It combines the identity template with a template that transforms the (full) name()s of the elements to their local-name()s only. That means all <ns1:abc> elements are transformed to <abc>, for example. The namespaces are omitted.

However, how useful this is depends on your usecase. It reduces the amount of information, so handle with care.

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

    <xsl:template match="node()|@*">   <!-- Identity template copies all nodes (except for elements, which are handled by the other template) -->
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*">           <!-- Removes all namespaces from all elements -->
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="node()|@*" />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

Apply it with an XSLT-1.0 (or above) framework/processor.


Post a Comment for "Remove All Namespaces From Xml"