解組XML 中的陣列元素:擷取所有元素,而不僅僅是第一個
在Golang 中使用xml.Unmarshal解組XML 數組時( []byte(p.Val.Inner), &t),您可能會遇到僅檢索第一個元素的情況。若要解決此問題,請利用 xml.Decoder 並重複呼叫其 Decode 方法。
解組所有 XML 陣列元素的步驟:
修改後的Golang 程式碼:
<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>
範例輸出:
[{ 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}}]
範例輸出:
範例輸出:以上是如何在 Golang 中檢索 XML 陣列中的所有元素而不僅限於第一個元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!