尝试在 Golang 中解析 XML,但得到了空的结构体。

huangapple go评论82阅读模式
英文:

Trying to parse xml in golang but getting empty struct

问题

我正在尝试解析一个 XML 文件,但是读取文件后我的 XML 结构为空。输出显示索引超出范围的错误。

英文:

im trying to parse an xml:

attaching xml since its too long for herehttps://drive.google.com/file/d/1CPleC1gBAR6n7lcyiR_zVMEjkowo3gUU/view?usp=sharing

type L1CProduct struct {
	XMLName xml.Name `xml:"n1:Level-1C_User_Product"`
	N1GeneralInfo N1GeneralInfo `xml:"n1:General_Info"`
}

type N1GeneralInfo struct {
	XMLName xml.Name `xml:"n1:General_Info"`
	ProductInfo ProductInfo `xml:"Product_Info"`
	SpectralInformationList SpectralInformationList `xml:"Product_Image_Characteristic>Spectral_Information_List"`
}

type SpectralInformationList struct {
	XMLName xml.Name `xml:"Spectral_Information_List"`
	SpectralInformation []SpectralInformation `xml:"Spectral_Information"`
}

type SpectralInformation struct {
	XMLName xml.Name `xml:"Spectral_Information"`
	BandId string `xml:"bandId,attr"`
	PhysicalBand string `xml:"physicalBand,attr"`
}

type ProductInfo struct{
	XMLName xml.Name `xml:"Product_Info"`
	ProductStartTime string `xml:"PRODUCT_START_TIME"`
	GenerationTime string `xml:"GENERATION_TIME"`
	ProductUri string `xml:"PRODUCT_URI"`

}

func parseXml() {
	// Open our xmlFile

	// xmlPath := inProcessPath + "/MTD_MSIL1C.xml"
	xmlPath := "/home/htc/Lizer/backend/InProcessResults/MTD_MSIL1C.xml"
    xmlFile, err := os.Open(xmlPath)
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Successfully Opened " + xmlPath)
    // defer the closing of our xmlFile so that we can parse it later on
    defer xmlFile.Close()

    // read our opened xmlFile as a byte array.
    byteValue, _ := ioutil.ReadAll(xmlFile)
	fmt.Printf("\nData: %s", byteValue)
    // we initialize our Users array
    var users L1CProduct
    // we unmarshal our byteArray which contains our
    // xmlFiles content into 'users' which we defined above
    xml.Unmarshal(byteValue, &users)
	fmt.Println(users.N1GeneralInfo.ProductInfo.ProductStartTime + "º")
	println(users.N1GeneralInfo.SpectralInformationList.SpectralInformation[1].BandId)
    // we iterate through every user within our users array and
    // print out the user Type, their name, and their facebook url
    // as just an example
    // for i := 0; i < len(users.N1GeneralInfo.SpectralInformationList.SpectralInformation); i++ {
	// for i := 0; i < 10; i++ {
    //     fmt.Println("Band Id: " + users.N1GeneralInfo.SpectralInformationList.SpectralInformation[i].BandId)
    //     fmt.Println("physicalBand: " + users.N1GeneralInfo.SpectralInformationList.SpectralInformation[i].PhysicalBand)
    // }

}

but while the file is read correctly mi xml structures are empty

fmt.Println(users.N1GeneralInfo.ProductInfo.ProductStartTime + "º")
	println(users.N1GeneralInfo.SpectralInformationList.SpectralInformation[1].BandId)

fmt.Println(users.N1GeneralInfo.ProductInfo.ProductStartTime + "º")
println(users.N1GeneralInfo.SpectralInformationList.SpectralInformation[1].BandId)

its like the struct is empty:
output : **

> º panic: runtime error: index out of range goroutine 1 [running]:
> main.parseXml()
> /home/htc/Lizer/backend/app/pkg/Services/Bandwith/service.go:164
> +0x3fd main.main()
> /home/htc/Lizer/backend/app/pkg/Services/Bandwith/service.go:53
> +0x20**

exit status 2

答案1

得分: 0

如果你想在XML中解析:,像这样:

xml:"n1:Level-1C_User_Product"

应该改为:

xml:"https://psd-14.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd Level-1C_User_Product"

参考:在Go中解析带有“:”的标签的XML

以下是一个示例:

package main

import (
	"encoding/xml"
	"fmt"
	"os"
)

type L1CProduct struct {
	XMLName       xml.Name `xml:"https://psd-14.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd Level-1C_User_Product"`
	N1GeneralInfo N1GeneralInfo
}

type N1GeneralInfo struct {
	XMLName     xml.Name    `xml:"https://psd-14.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd General_Info"`
	ProductInfo ProductInfo `xml:"Product_Info"`
}
type ProductInfo struct {
	XMLName          xml.Name `xml:"Product_Info"`
	ProductStartTime string   `xml:"PRODUCT_START_TIME"`
	GenerationTime   string   `xml:"GENERATION_TIME"`
	ProductUri       string   `xml:"PRODUCT_URI"`
}

func parseXml() {
	// 打开我们的xml文件

	// xmlPath := inProcessPath + "/MTD_MSIL1C.xml"
	xmlPath := "./MTD_MSIL1C.xml"
	// 将打开的xml文件读取为字节数组。
	byteValue, _ := os.ReadFile(xmlPath)
	// 初始化我们的Users数组
	var users L1CProduct

	err := xml.Unmarshal(byteValue, &users)
	if err != nil {
		fmt.Printf("%v\n", err)
	}
	fmt.Println(users.N1GeneralInfo.ProductInfo.ProductStartTime + "°")
}

func main() {
	parseXml()
}

以下是输出:

2022-11-09T16:55:19.024Z°

英文:

if you want parser : in xml

like

xml:"n1:Level-1C_User_Product"

should be:

xml:"https://psd-14.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd Level-1C_User_Product"

see: Parse Xml in GO for atttribute with ":" in tag

follow is a demo:

package main

import (
	"encoding/xml"
	"fmt"
	"os"
)

type L1CProduct struct {
	XMLName       xml.Name `xml:"https://psd-14.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd Level-1C_User_Product"`
	N1GeneralInfo N1GeneralInfo
}

type N1GeneralInfo struct {
	XMLName     xml.Name    `xml:"https://psd-14.sentinel2.eo.esa.int/PSD/User_Product_Level-1C.xsd General_Info"`
	ProductInfo ProductInfo `xml:"Product_Info"`
}
type ProductInfo struct {
	XMLName          xml.Name `xml:"Product_Info"`
	ProductStartTime string   `xml:"PRODUCT_START_TIME"`
	GenerationTime   string   `xml:"GENERATION_TIME"`
	ProductUri       string   `xml:"PRODUCT_URI"`
}

func parseXml() {
	// Open our xmlFile

	// xmlPath := inProcessPath + "/MTD_MSIL1C.xml"
	xmlPath := "./MTD_MSIL1C.xml"
	// read our opened xmlFile as a byte array.
	byteValue, _ := os.ReadFile(xmlPath)
	// we initialize our Users array
	var users L1CProduct

	err := xml.Unmarshal(byteValue, &users)
	if err != nil {
		fmt.Printf("%v\n", err)
	}
	fmt.Println(users.N1GeneralInfo.ProductInfo.ProductStartTime + "º")
}

func main() {
	parseXml()
}

follow is output:

2022-11-09T16:55:19.024Zº

huangapple
  • 本文由 发表于 2022年11月11日 03:04:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/74394151.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定