Skip to content

encoding/xml: Serializing XML with namespace prefix #11496

Open
@olivere

Description

@olivere

Hi!

I'm struggling with serializing XML (and deserializing again).

But first things first:

go version devel +434e0bc Mon Jun 29 16:07:14 2015 +0000 darwin/amd64  # (tried 1.4 and master)
Darwin aero 14.4.0 Darwin Kernel Version 14.4.0: Thu May 28 11:35:04 PDT 2015; root:xnu-2782.30.5~1/RELEASE_X86_64 x86_64

I'm trying to serialize a struct to generate XML like this (see http://play.golang.org/p/fMvL86lzB0):

<person xmlns="ns1" xmlns:ns2="ns2">
  <name>Oliver</name>
  <ns2:phone>110</ns2:phone>
</person>

When defining Person like this ...

type Person struct {
    XMLName xml.Name `xml:"ns1 person"`
    Name    string   `xml:"name"`
    Phone   string   `xml:"ns2 phone,omitempty"`
}

... it serialized into the following (which is semantically correct, I guess, but not the same as above):

<person xmlns="ns1">
  <name>Oliver</name>
  <phone xmlns="ns2">110</phone>
</person>

I can fake it like this:

type Person struct {
    XMLName xml.Name `xml:"ns1 person"`
    NS2 string `xml:"xmlns:ns2,attr"`

    Name    string   `xml:"name"`
    Phone   string   `xml:"ns2:phone,omitempty"`
}

... by initializing NS2 before serializing (see http://play.golang.org/p/2dEljm97c8). Unfortunately then I'm not able to deserialize correctly as the Phone field will not be blank (see http://play.golang.org/p/RxG2ImcWbm).

Maybe it's just a documentation issue and I'm missing an example. There are some other issues regarding XML and namespaces/namespace prefixes (e.g. #6800, #9519, #7113) some of which are closed and some of which are open, so I'm a bit confused about the status.

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.help wanted

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions