Skip to content

encoding/xml: support QName values / expose namespace bindings #12406

Open
@pdw-mb

Description

@pdw-mb

It's not uncommon for XML to contain QNames as element and attribute values, e.g.

  <my-document xmlns:foo="http//..." >
    <my-element>foo:bar</my-element>
  </my-document>

In order to correctly unmarshal the value, you need to know the namespace bindings in effect for my-element, but Decoder doesn't appear to expose this information. A simple addition to encoding/xml of:

  func (d *Decoder) NamespaceBindings() map[string]string {
    return d.ns
  }

allows unmarshallers to access the necessary information, for example, I can now write:

  type QName struct {
    Namespace string
    Local     string
  } 

 func (qname *QName) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    var s string
    d.DecodeElement(&s, &start)
    i := strings.Index(s, ":")
    prefix := ""
    if i >= 0 {
      prefix = s[:i]
      qname.Namespace = s[i+1:]
    } else {
      qname.Namespace = s
    }
    var ok bool
    qname.Namespace, ok = d.NamespaceBindings()[prefix]
    if !ok {
      return errors.New("Unbound namespace prefix: " + prefix)
    }
    return nil
  }

Arguably, something like the above, and a corresponding attribute unmarshaller could be provided on the standard xml.Name.

More discussion of this issue here:

https://groups.google.com/forum/#!searchin/golang-nuts/QName/golang-nuts/DexmVLQOJxk/whBaKK9ntHsJ

go version go1.5 darwin/amd64

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsFixThe path to resolution is known, but the work has not been done.Thinkingearly-in-cycleA change that should be done early in the 3 month dev cycle.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions