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:
<code class="go">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>`</code>
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.
The above is the detailed content of How to Retrieve All Elements in an XML Array in Golang without Limiting to Just the First Element?. For more information, please follow other related articles on the PHP Chinese website!