Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML unmarshal does not respect the root element namespace prefix definition

Tags:

xml-parsing

go

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!

like image 910
Wilson Wang Avatar asked Sep 21 '15 22:09

Wilson Wang


1 Answers

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.

like image 191
Jeremy Huiskamp Avatar answered Oct 16 '22 16:10

Jeremy Huiskamp