Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: encoding/xml: access to ns short codes #64740

Open
dhubler opened this issue Dec 15, 2023 · 0 comments
Open

proposal: encoding/xml: access to ns short codes #64740

dhubler opened this issue Dec 15, 2023 · 0 comments
Labels
Milestone

Comments

@dhubler
Copy link

dhubler commented Dec 15, 2023

Proposal Details

I would like access to the namespace short codes to long form mappings used during an unmarshaling. This is useful for processing custom element and attribute values that reference the short codes like xpaths in IETF RFC6241 NETCONF

Example:

<x xmlns:z="zee">
  <y xpath="z:banana/foo/z:apple"></y>
</x>

Here I need to parse xpath and lookup that z's full namespace is zee

Fix: to encoding/xml/xml.go

// LookupNs will return the full namespace string give a short code. This will
// only be useful from implementations of Unmarshaler while the namespaces
// are still in scope
func (d *Decoder) LookupNs(shortcode string) string {
	return d.ns[shortcode]
}

Example:

func TestXpath(t *testing.T) {
	x := struct {
		Y *Y `xml:"y"`
	}{}
	orig := `<x xmlns:z="zee">
	  <y xpath="z:banana/foo/z:apple"></y>
	</x>`
	d := xml.NewDecoder(strings.NewReader(orig))
	if err := d.Decode(&x); err != nil {
		t.Fail()
	}
	if x.Y.XPathLookup != "z=zee" {
		t.Error(x.Y.XPathLookup)
	}
}

type Y struct {
	XPath       string
	XPathLookup string
}

func (y *Y) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	copy := struct {
		XPath string
	}{}
	if err := d.DecodeElement(&copy, &start); err != nil {
		return err
	}
	y.XPath = copy.XPath
	y.XPathLookup = fmt.Sprintf("z=%s", d.LookupNs("z"))
	return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

2 participants