I try to parse xml file that has elements with arbitrary endings
Example of xml with Array0 and Array1:
<GetPriceChangesForReseller>
<PriceContractArray0 actualtype="PriceContract">
<EndUserPrice>1990,00</EndUserPrice>
</PriceContractArray0>
<PriceContractArray1 actualtype="PriceContract">
<EndUserPrice>2290,00</EndUserPrice>
</PriceContractArray1>
</GetPriceChangesForReseller>
How can I work with this case?
a part of my code:
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)
}
Thanks in advance!
You can use the following structure (try it online!):
type GetPriceChangesForReseller struct {
XMLName xml.Name `xml:"GetPriceChangesForReseller"`
Items []PriceContract `xml:",any"`
}
type PriceContract struct {
Price string `xml:"EndUserPrice"`
}
It should work.
you can try xmlquery, its easy to parse and query for XML document , without defined types like structs.
doc, err := xmlquery.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
for _, n := range xmlquery.Find(doc, "//GetPriceChangesForReseller/*") {
fmt.Printf("%s price: %s
", n.Data, n.SelectElement("EndUserPrice").InnerText())
}
PriceContractArray0 price: 1990,00
PriceContractArray1 price: 2290,00