在 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