Unmarshal Array Elements in XML: Retrieve All Elements, Not Just the First
When unmarshaling an XML array in Golang using xml.Unmarshal([]byte(p.Val.Inner), &t), you may encounter a situation where only the first element is being retrieved. To resolve this issue, utilize xml.Decoder and repeatedly invoke its Decode method.
Steps to Unmarshal All XML Array Elements:
Modified Golang Code:
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"log"
)
type HostSystemIdentificationInfo []struct {
IdentiferValue string `xml:"identifierValue"`
IdentiferType struct {
Label string `xml:"label"`
Summary string `xml:"summary"`
Key string `xml:"key"`
} `xml:"identifierType"`
}
func main() {
d := xml.NewDecoder(bytes.NewBufferString(VV))
for {
var t HostSystemIdentificationInfo
err := d.Decode(&t)
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
}
}
const VV = `<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
<identifierValue> unknown</identifierValue>
<identifierType>
<label>Asset Tag</label>
<summary>Asset tag of the system</summary>
<key>AssetTag</key>
</identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
<identifierValue>Dell System</identifierValue>
<identifierType>
<label>OEM specific string</label>
<summary>OEM specific string</summary>
<key>OemSpecificString</key>
</identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
<identifierValue>5[0000]</identifierValue>
<identifierType>
<label>OEM specific string</label>
<summary>OEM specific string</summary>
<key>OemSpecificString</key>
</identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
<identifierValue>REDACTED</identifierValue>
<identifierType>
<label>Service tag</label>
<summary>Service tag of the system</summary>
<key>ServiceTag</key>
</identifierType>
</HostSystemIdentificationInfo>`
Sample Output:
[{ unknown {Asset Tag Asset tag of the system AssetTag}}] [{Dell System {OEM specific string OEM specific string OemSpecificString}}] [{5[0000] {OEM specific string OEM specific string OemSpecificString}}] [{REDACTED {Service tag Service tag of the system ServiceTag}}]
By using xml.Decoder and repeatedly invoking Decode, you can successfully retrieve all elements within the XML array, resolving the issue of only obtaining the first element.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3