Go 如何在解组时跳过元素?
在解组XML时,如何删除Go 如何在解组时跳过元素?,go,Go,在解组XML时,如何删除…(如下所示) 我尝试使用UnmarshalXML方法跳过元素,但是,当我这样做时,它会跳过整个元素 包干管 import ( "encoding/xml" "fmt" ) type Root struct { Translation []Text `xml:"Texts>Text>Text"` } type Text struct { Language string `xml:"Language,attr"` V
…
(如下所示)
我尝试使用UnmarshalXML
方法跳过元素,但是,当我这样做时,它会跳过整个元素
包干管
import (
"encoding/xml"
"fmt"
)
type Root struct {
Translation []Text `xml:"Texts>Text>Text"`
}
type Text struct {
Language string `xml:"Language,attr"`
Value string `xml:"Value"`
}
func main() {
foo := `
<Root>
<Texts>
<Text>
<Text Language="EN">
<Value>One</Value>
</Text>
<Text Language="de">
<Value>Eins</Value>
</Text>
</Text>
</Texts>
</Root>
`
var root Root
e := xml.Unmarshal([]byte(foo), &root)
if e != nil {
panic(e)
}
fmt.Printf("%+v\n", root)
}
func (t *Text) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
tx := struct{ Language, Value string }{}
if start.Attr[0].Value == "EN" {
d.DecodeElement(&tx, &start)
// I couldn't got Language attr here
*t = Text{tx.Language, tx.Value}
// fmt.Printf("hey: %+v %s\n", tx, start.Attr[0].Value)
} else {
// It outputs DE element with empty fields
d.Skip()
}
return nil
}
我想要什么:
{Translation:[{Language: Value:One} {Language: Value:}]}
{Translation:[{Language:EN Value:One}]}
通过在文本级别解组,您的操作太低-您仍然在解组2个文本元素,这就是为什么您看到第二个元素为空。您可以尝试以下方法:
package main
import (
"encoding/xml"
"fmt"
)
type Root struct {
Translation Text `xml:"Texts>Text>Text"`
}
type Text []struct {
Language string `xml:"Language,attr"`
Value string `xml:"Value"`
}
func main() {
foo := `
<Root>
<Texts>
<Text>
<Text Language="EN">
<Value>One</Value>
</Text>
<Text Language="de">
<Value>Eins</Value>
</Text>
</Text>
</Texts>
</Root>
`
var root Root
e := xml.Unmarshal([]byte(foo), &root)
if e != nil {
panic(e)
}
fmt.Printf("%+v\n", root)
}
func (t *Text) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
tx := []struct{
Language string `xml:"Language,attr"`
Value string `xml:"Value"`
}{}
d.DecodeElement(&tx, &start)
tSl := *t
for _, elem := range tx {
switch elem.Language {
case "EN":
tSl = append(tSl, struct{
Language string `xml:"Language,attr"`
Value string `xml:"Value"`}{elem.Language, elem.Value})
default:
d.Skip()
}
}
*t = tSl
return nil
}
普通解组和后处理。
{Translation:[{Language:EN Value:One}]}