1

I have some XML:

<Root>
 <Name>Eding</Name>
 <Roll>15</Roll>
 <xyz:Address>25, Brigton,SA</xyz:Address>
</Root>

This xml is not valid as the namespace xyz is not defined. So, I want to add the namespace in the root using xslt.

How can I do that?

0

2 Answers 2

2

XSLT will only take namespace-well-formed XML as input. So if your input isn't namespace-well-formed, you can't solve the problem with XSLT.

Sign up to request clarification or add additional context in comments.

Comments

0

One way to solve this is through the use of an external (parsed) general entity.

You could "wrap" the invalid XML file with an XML document that declares the xyz namespace-prefix and then includes the content of your file using an external entity. Then transform the file to remove the wrapped content and produce the desired output.

For this example, your example file is referred to as fragment.xml. I defined an external entity pointing to the file and then reference it inside of the wrapper element. The wrapper element has the xyz namespace prefix defined:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE wrapper [
<!ENTITY otherFile SYSTEM "fragment.xml">
]>
<wrapper xmlns:xyz="http://stackoverflow.com/questions/12024763/how-can-i-add-a-namespace-xmlnsxyz-to-an-xml-document-using-xslt">
&otherFile;
</wrapper>

When parsed by any XML parser, the document will be "seen" as:

<wrapper xmlns:xyz="http://stackoverflow.com/questions/12024763/how-can-i-add-a-namespace-xmlnsxyz-to-an-xml-document-using-xslt">
<Root>
    <Name>Eding</Name>
    <Roll>15</Roll>
    <xyz:Address>25, Brigton,SA</xyz:Address>
</Root>
</wrapper>

Then, use a modified identity transform with a template to remove the wrapper element:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0">

    <!--identity template to copy all content forward by default -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <!--remove the "wrapper" element, then process the rest of the content -->
    <xsl:template match="/wrapper">
        <xsl:apply-templates/>
    </xsl:template>

</xsl:stylesheet>

Producing the following output:

<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xyz="http://stackoverflow.com/questions/12024763/how-can-i-add-a-namespace-xmlnsxyz-to-an-xml-document-using-xslt">
    <Name>Eding</Name>
    <Roll>15</Roll>
    <xyz:Address>25, Brigton,SA</xyz:Address>
</Root>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.