Problem
我需要将XML
从第三方应用程序解组到我的GO struct .
what i tried
我创建了 struct ,并且能够从我的代码中生成相同的XML
.
ValidXML
我简化了这个示例的xml:
<Parent>
<Name>tic.TEST</Name>
<MetaData>
<LawFormID Type="129" DefinedSize="3">DOO</LawFormID>
<FirmUQ Type="129" DefinedSize="15">BARTOG</FirmUQ>
<FirmDescription Type="200" DefinedSize="100">Bartog d.o.o. Trebnje</FirmDescription>
</MetaData>
</Parent>
Structs
我对应的 struct 如下.
type Parent struct {
Name string
MetaData []Node `xml:"MetaData>any"`
}
type Node struct {
XMLName xml.Name // this allows custom node names
Type int `xml:"Type,attr,omitempty"`
DefinedSize int `xml:"DefinedSize,attr,omitempty"`
Text string `xml:",chardata"` // required at some places, cannot omit
}
@TestMetadata_Marshal
func TestMetaData_Marshal(t *testing.T) {
parent := Parent{
Name: "tic.TEST",
MetaData: []Node{
{
XMLName: xml.Name{
Local: "LawFormID",
},
Text: "DOO",
Type: 129,
DefinedSize: 3,
}, {
XMLName: xml.Name{
Local: "FirmUQ",
},
Text: "BARTOG",
Type: 129,
DefinedSize: 15,
}, {
XMLName: xml.Name{
Local: "FirmDescription",
},
Text: "Bartog d.o.o. Trebnje",
Type: 200,
DefinedSize: 100,
},
}, // \MetaData
}
HaveXML := XML(parent)
fmt.Println(HaveXML)
if ValidXML != HaveXML {
t.Error(fmt.Errorf("marshaled XML did not match. Have: %v", HaveXML))
}
}
Unmarshal
this is where the troubles begin; the test func
is trivial; result is that no entries in MetaData
are available.
I tried a lot of different tag
s, also tried creating an own MetaData
struct
containing Items []Node
func TestUnmarshal() {
var parent Parent
err := xml.Unmarshal([]byte(ValidXML), &parent)
if err != nil {
fmt.Println(err)
return
}
HaveXML := XML(parent)
if ValidXML == HaveXML {
fmt.Println("\tmarshaled XML is Valid")
} else {
fmt.Printf("\tmarshaled XML did not match. Have:\n%v\n", HaveXML)
}
}
go play (turned tests into 'normal' funcs
https://goplay.tools/snippet/kWS29HR7O9t
Question
在go&;中不可能做到这一点吗;xml?