Home >Backend Development >Golang >How to Unmarshal XML Elements with Attributes and Floating-Point Values into Go Structs?

How to Unmarshal XML Elements with Attributes and Floating-Point Values into Go Structs?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 02:40:29966browse

How to Unmarshal XML Elements with Attributes and Floating-Point Values into Go Structs?

Unmarshaling XML Elements into Go structs

Consider the following XML element, which includes an attribute and a floating-point value:

<thing prop="1">
  1.23
</thing>
<thing prop="2">
  4.56
</thing>

To unmarshal this XML into a Go struct, two design approaches can be used:

With XMLName Property:

<code class="go">type ThingElem struct {
    XMLName xml.Name `xml:"thing"`
    Prop    int      `xml:"prop,attr"`
    Value   float64 // ???
}</code>

In this case, the XMLName field is used to specify that the struct represents the "thing" XML element. However, it's not always necessary to include this field in the struct definition.

Without XMLName Property:

<code class="go">type ThingElem struct {
    Prop  int   `xml:"prop,attr"`
    Value float64 // ???
}

type ThingWrapper struct {
    T ThingElem `xml:"thing"`
}</code>

In this approach, the ThingElem struct is unmarshaled within a wrapper struct ThingWrapper. The xml:"thing" tag on the wrapper struct designates that the ThingElem should represent the "thing" XML element.

Determining Value Field Type:

When defining the Value field, it's important to note that the XML element contains character data (text content) representing the floating-point value. To correctly unmarshal this, the following changes must be made:

Remove Spaces from Value:

The XML data contains spaces within the floating-point values. These spaces must be removed before unmarshaling.

Use ",chardata" Annotation:

The contents of the XML tag can be referenced using the ",chardata" annotation in the struct field definition:

<code class="go">Value float64 `xml:",chardata"`</code>

By incorporating these modifications and ensuring that the XML data is trimmed of spaces, you can successfully unmarshal the given XML into a Go struct using either of the design approaches mentioned above.

The above is the detailed content of How to Unmarshal XML Elements with Attributes and Floating-Point Values into Go Structs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn