I want to parse the attribute of an Xml file. It works for any "normal" attributes like for instance <application name="AppName">
But I can't manage to retrieve the value of the attribute if it has a ":" in it., like <application name:test="AppName">
Here is the code that I am using to parse this :
package main
import "fmt"
import "encoding/xml"
type Application struct {
Event Event `xml:"application"`
Package string `xml:"package,attr"`
}
type Event struct {
IsValid string `xml:"test:isValid,attr"`
}
var doc = []byte(`<?xml version="1.0" encoding="utf-8" standalone="no"?>
<application package="leNomDuPackage">
<event test:isValid="true">
</application>
</manifest>`)
func main() {
application := Application{}
xml.Unmarshal(doc, &application)
fmt.Println("Application: ", application)
fmt.Println("isValid:", application.Event)
}
You can find it on the Golang playground as well : [https://play.golang.org/p/R6H80xPezhm
I want to retrieve the value of the isValid
attribute.
At the moment, I have that error message and I can't manage to solve it.
struct field tag
xml:"test\:isValid,attr
not compatible with reflect.StructTag.Get: bad syntax for struct tag value
I tried as well with the following value of
type Event struct {
IsValid string `xml:"test isValid,attr`
}
and
type Event struct {
IsValid string `xml:"test\:isValid,attr`
}
But it is not working as well.
You can leave out the "test:"
prefix in the tag definition. Just make sure your XML is valid, yours don't have a closing tag for <event>
and has an unmatched closing tag </manifest>
. You're also missing a closing quotation mark in the tag definition.
Model:
type Application struct {
Event Event `xml:"event"`
Package string `xml:"package,attr"`
}
type Event struct {
IsValid string `xml:"isValid,attr"`
}
A valid XML example:
var doc = `
<application package="leNomDuPackage">
<event test:isValid="true" />
</application>`
Code parsing it:
application := Application{}
err := xml.Unmarshal([]byte(doc), &application)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Application: %#v
", application)
Output (try it on the Go Playground):
Application: main.Application{Event:main.Event{IsValid:"true"},
Package:"leNomDuPackage"}
Note that if you have multiple attributes with the same name but different prefixes, such as this example:
var doc = `
<application package="leNomDuPackage">
<event test:isValid="true" test2:isValid="false" />
</application>`
Then you may add the namespace prefix in the tag value, separated by a space from the name, like this:
type Event struct {
IsValid1 string `xml:"test isValid,attr"`
IsValid2 string `xml:"test2 isValid,attr"`
}
Parsing code is the same. Output (try it on the Go Playground):
Application: main.Application{Event:main.Event{IsValid1:"true",
IsValid2:"false"}, Package:"leNomDuPackage"}