在GO XML中解析具有任意结局的元素

  • 本文关键字:任意结 元素 GO XML xml go
  • 更新时间 :
  • 英文 :


我尝试解析具有任意结局元素的XML文件

xml的示例带有array0和array1:

<GetPriceChangesForReseller>
          <PriceContractArray0 actualtype="PriceContract">
            <EndUserPrice>1990,00</EndUserPrice>     
          </PriceContractArray0>
          <PriceContractArray1 actualtype="PriceContract">        
            <EndUserPrice>2290,00</EndUserPrice>
          </PriceContractArray1>  
</GetPriceChangesForReseller>

我该如何处理这种情况?

我代码的一部分:

package main
import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "os"
)

type GetPriceChangesForReseller struct {
    XMLName                    xml.Name             `xml:"GetPriceChangesForReseller"`
    GetPriceChangesForReseller []PriceContractArray `xml:"PriceContractArray"`
}

type PriceContractArray struct {
    XMLName             xml.Name `xml:"PriceContractArray"`
    Price               string   `xml:"Price"`
func main() {
// Open our xmlFile
xmlFile, err := os.Open("GetPriceChangesForReseller.xml")
// if we os.Open returns an error then handle it
if err != nil {
    fmt.Println(err)
}

预先感谢!

您可以使用以下结构(在线尝试!):

type GetPriceChangesForReseller struct {
    XMLName xml.Name        `xml:"GetPriceChangesForReseller"`
    Items   []PriceContract `xml:",any"`
}
type PriceContract struct {
    Price string `xml:"EndUserPrice"`
}

它应该起作用。

您可以尝试XMLQUERY,它易于解析和查询XML文档,而没有诸如结构之类的定义类型。

doc, err := xmlquery.Parse(strings.NewReader(s))
    if err != nil {
        panic(err)
    }
    for _, n := range xmlquery.Find(doc, "//GetPriceChangesForReseller/*") {
        fmt.Printf("%s price: %sn", n.Data, n.SelectElement("EndUserPrice").InnerText())
    }

PriceContractArray0价格:1990,00

PriceContractArray1价格:2290,00

最新更新