Configuring XML parsing and serialization

suggest change

You can modify how a struct is serialized to XML by annotating fields with tags.

By providing XMLName, this will be serialized as <data>...</data> and not <ShowXMLName>..</ShowXMLName>.

main.go

type ShowXMLName struct {
	XMLName xml.Name `xml:"data"`
	N       int      `xml:"n"`
}

	v := &ShowXMLName{
		N: 5,
	}
	printXML(v)

Output:

XML: <data><n>5</n></data>

Fields marked with xml:"-" are not serialized.

main.go

type ShowOmit struct {
	Name          string `xml:"name"`
	NotSerialized string `xml:"-"`
}

	v := &ShowOmit{
		Name:          "John",
		NotSerialized: "Connor",
	}
	printXML(v)

Output:

XML: <ShowOmit><name>John</name></ShowOmit>

To skip serializing fields with empty values, use xml:",omitempty".

main.go

type ShowOmitEmpty struct {
	NonEmpty string `xml:",omitempty"`
	Empty    string `xml:",omitempty"`
}

	v := &ShowOmitEmpty{
		NonEmpty: "non empty",
		Empty:    "",
	}
	printXML(v)

Output:

XML: <ShowOmitEmpty><NonEmpty>non empty</NonEmpty></ShowOmitEmpty>

To change serialization from XML element to XML attribute use xml:",attr".

main.go

type ShowAttr struct {
	B bool `xml:"n,attr"`
}

	v := &ShowAttr{
		B: true,
	}
	printXML(v)

Output:

XML: <ShowAttr n="true"></ShowAttr>

To change serialization from XML element to character data use xml:",chardata".

main.go

type ShowCharData struct {
	S string `xml:",chardata"`
}

	v := &ShowCharData{
		S: "str",
	}
	printXML(v)

Output:

XML: <ShowCharData>str</ShowCharData>

To change serialization from XML element to CDATA use xml:",cdata".

main.go

type ShowCData struct {
	S string `xml:",cdata"`
}

	v := &ShowCData{
		S: "cdata",
	}
	printXML(v)

Output:

XML: <ShowCData><![CDATA[cdata]]></ShowCData>

To serialize the value verbatim, use xml:",innerxml".

main.go

type ShowInnerXML struct {
	Str string `xml:"s"`
	Raw string `xml:",innerxml"`
}

	v := &ShowInnerXML{
		Str: "<foo></foo>",
		Raw: "<foo></foo>",
	}
	printXML(v)

Output:

XML: <ShowInnerXML><s>&lt;foo&gt;&lt;/foo&gt;</s><foo></foo></ShowInnerXML>

To serialize field as XML comment, use xml:",comment". Value can’t contain --.

main.go

type ShowComment struct {
	Str string `xml:",comment"`
}

	v := &ShowComment{
		Str: "comment",
	}
	printXML(v)

Output:

XML: <ShowComment><!--comment--></ShowComment>

xml:"a>b>str" nests XML element. This also influences parsing.

main.go

type ShowNesting struct {
	Str string `xml:"a>b>str"`
}

	v := &ShowNesting{
		Str: "str",
	}
	printXML(v)

Output:

XML: <ShowNesting><a><b><str>str</str></b></a></ShowNesting>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents