Wilson Wang
Wilson Wang

Reputation: 111

XML unmarshal does not respect the root element namespace prefix definition

Here is the XML structure:

<root xmlns:test="http://test.com/testns">
            <test:sub>
                <title>this is title</title>
            </test:sub>
</root>

It gets unmarshalled with the structs defined below:

type Root struct {
    XMLName xml.Name `xml:"root"`
    Sub *Sub
}

type Sub struct {
    XMLName       xml.Name `xml:"http://test.com/testns sub"`
    Title         string   `xml:"title"` 
}

This is what gets marshalled back:

<root>
    <sub xmlns="http://test.com/testns">
        <title>this is title</title>
    </sub>
</root>

The root namespace prefix definition gets removed after the marshal and the sub element is using url namespace instead of the prefix. Here is the code

Is there any way that marshal/unmarshal won't change the xml structure? thanks!

Upvotes: 6

Views: 1578

Answers (1)

Jeremy Huiskamp
Jeremy Huiskamp

Reputation: 5304

It doesn't look like it changed the logical structure. In your original input, the root element declares a prefix test for the namespace http://test.com/testns but it doesn't actually declare itself to be in that namespace.

Here's an alternate version that does what it looks like you want: https://play.golang.org/p/NqNyIyMB4IP

I bumped the namespace up to the Root struct and added the test: prefix to the root xml element in the input.

Upvotes: 1

Related Questions