在XML 中解組數組元素:檢索所有元素,而不僅僅是第一個
當使用xml.Unmarshal( 在Golang 中解組XML 陣列時[]byte(p.Val.Inner), &t),您可能會遇到僅檢索第一個元素的情況。若要解決此問題,請利用 xml.Decoder 並重複呼叫其 Decode 方法。
解組所有 XML 陣列元素的步驟:
修改的Golang 代碼:
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>`
範例輸出:
[{ 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}}]
透過使用xml.Decoder,重複呼叫Decode,可以成功擷取XML陣列中的所有元素,解決了只能取得第一個的問題元素。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3