Configuring XML parsing and serialization
suggest changeYou 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>
.
type ShowXMLName struct {
XMLName xml.Name `xml:"data"`
N int `xml:"n"`
}
v := &ShowXMLName{
N: 5,
}
printXML(v)
XML: <data><n>5</n></data>
Fields marked with xml:"-"
are not serialized.
type ShowOmit struct {
Name string `xml:"name"`
NotSerialized string `xml:"-"`
}
v := &ShowOmit{
Name: "John",
NotSerialized: "Connor",
}
printXML(v)
XML: <ShowOmit><name>John</name></ShowOmit>
To skip serializing fields with empty values, use xml:",omitempty"
.
type ShowOmitEmpty struct {
NonEmpty string `xml:",omitempty"`
Empty string `xml:",omitempty"`
}
v := &ShowOmitEmpty{
NonEmpty: "non empty",
Empty: "",
}
printXML(v)
XML: <ShowOmitEmpty><NonEmpty>non empty</NonEmpty></ShowOmitEmpty>
To change serialization from XML element to XML attribute use xml:",attr"
.
type ShowAttr struct {
B bool `xml:"n,attr"`
}
v := &ShowAttr{
B: true,
}
printXML(v)
XML: <ShowAttr n="true"></ShowAttr>
To change serialization from XML element to character data use xml:",chardata"
.
type ShowCharData struct {
S string `xml:",chardata"`
}
v := &ShowCharData{
S: "str",
}
printXML(v)
XML: <ShowCharData>str</ShowCharData>
To change serialization from XML element to CDATA use xml:",cdata"
.
type ShowCData struct {
S string `xml:",cdata"`
}
v := &ShowCData{
S: "cdata",
}
printXML(v)
XML: <ShowCData><![CDATA[cdata]]></ShowCData>
To serialize the value verbatim, use xml:",innerxml"
.
type ShowInnerXML struct {
Str string `xml:"s"`
Raw string `xml:",innerxml"`
}
v := &ShowInnerXML{
Str: "<foo></foo>",
Raw: "<foo></foo>",
}
printXML(v)
XML: <ShowInnerXML><s><foo></foo></s><foo></foo></ShowInnerXML>
To serialize field as XML comment, use xml:",comment"
. Value can’t contain --
.
type ShowComment struct {
Str string `xml:",comment"`
}
v := &ShowComment{
Str: "comment",
}
printXML(v)
XML: <ShowComment><!--comment--></ShowComment>
xml:"a>b>str"
nests XML element. This also influences parsing.
type ShowNesting struct {
Str string `xml:"a>b>str"`
}
v := &ShowNesting{
Str: "str",
}
printXML(v)
XML: <ShowNesting><a><b><str>str</str></b></a></ShowNesting>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents