Golang XML解析

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

Golang XML parse

问题

我的XML数据:

<dictionary version="0.8" revision="403605">
    <grammemes>
        <grammeme parent="">POST</grammeme>
        <grammeme parent="POST">NOUN</grammeme>
    </grammemes>
</dictionary>

我的代码:

type Dictionary struct {
    XMLName xml.Name `xml:"dictionary"`
    Grammemes *Grammemes `xml:"grammemes"`
}

type Grammemes struct {
    Grammemes []*Grammeme `xml:"grammeme"`
}

type Grammeme struct {
    Name string `xml:"grammeme"`
    Parent string `xml:"parent,attr"`
}

我可以获取Grammeme.Parent属性,但无法获取Grammeme.Name属性。为什么?

英文:

My XML data:

&lt;dictionary version=&quot;0.8&quot; revision=&quot;403605&quot;&gt;
    &lt;grammemes&gt;
        &lt;grammeme parent=&quot;&quot;&gt;POST&lt;/grammeme&gt;
        &lt;grammeme parent=&quot;POST&quot;&gt;NOUN&lt;/grammeme&gt;
    &lt;/grammemes&gt;
&lt;/dictionary&gt;

My code:

type Dictionary struct {
	XMLName xml.Name `xml:&quot;dictionary&quot;`
	Grammemes *Grammemes `xml:&quot;grammemes&quot;`
}

type Grammemes struct {
	Grammemes []*Grammeme `xml:&quot;grammeme&quot;`
}

type Grammeme struct {
	Name string `xml:&quot;grammeme&quot;`
	Parent string `xml:&quot;parent,attr&quot;`
}

I get Grammeme.Parent attribute, but i don't get Grammeme.Name. Why?

答案1

得分: 12

如果你想要一个字段来保存当前元素的内容,你可以使用标签xml:"chardata"。根据你标记的结构,它实际上是在寻找一个<grammeme>子元素。

所以你可以解码成一组这样的结构体:

type Dictionary struct {
    XMLName   xml.Name   `xml:"dictionary"`
    Grammemes []Grammeme `xml:"grammemes>grammeme"`
}

type Grammeme struct {
    Name   string `xml:",chardata"`
    Parent string `xml:"parent,attr"`
}

你可以在这里测试这个例子:http://play.golang.org/p/7lQnQOCh0I

英文:

If you want a field to hold the contents of the current element, you can use the tag xml:&quot;,chardata&quot;. The way you've tagged your structure, it is instead looking for a &lt;grammeme&gt; sub-element.

So one set of structures you could decode into is:

type Dictionary struct {
	XMLName   xml.Name   `xml:&quot;dictionary&quot;`
	Grammemes []Grammeme `xml:&quot;grammemes&gt;grammeme&quot;`
}

type Grammeme struct {
	Name   string `xml:&quot;,chardata&quot;`
	Parent string `xml:&quot;parent,attr&quot;`
}

You can test out this example here: http://play.golang.org/p/7lQnQOCh0I

huangapple
  • 本文由 发表于 2014年3月26日 16:40:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/22655457.html
匿名

发表评论

匿名网友

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

确定