相同的 XML 标签具有不同属性的不同结构体

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

Different structs for same XML tag with different attributes

问题

假设我有这个XML:

<something>
  <value type="item">
    ...
  </value>
  <value type="other">
    ...
  </value>
</something>

我能否以某种方式将具有不同属性的值提取到结构体的不同字段中,例如:

type Something struct {
  Item  Item  `xml:"value[type=item]"` // 元代码
  Other Other `xml:"value[type=other]"`
}

这种做法可行吗?我应该使用什么作为xml:属性?

英文:

Let's say I have this XML:

&lt;something&gt;
  &lt;value type=&quot;item&quot;&gt;
    ...
  &lt;/value&gt;
  &lt;value type=&quot;other&quot;&gt;
    ...
  &lt;/value&gt;
&lt;/something&gt;

Can I somehow extract the value with different attributes to different items on my struct, like:

type Something struct {
  Item  Item  `xml:&quot;value[type=item]&quot;` // metacode
  Other Other `xml:&quot;value[type=other]&quot;`
}

Is it possible? What should I use as the xml: attribute?

答案1

得分: 1

我不认为直接将按属性值区分的项目列表映射到特定字段是可能的。你需要将其映射到一个切片,就像下面的示例中的Items切片一样:

package main

import (
	"encoding/xml"
	"fmt"
)

func main() {

	type Item struct {
		Type  string `xml:"type,attr"`
		Value string `xml:",chardata"`
	}

	type Something struct {
		XMLName xml.Name `xml:"something"`
		Name    string   `xml:"name"`
		Items   []Item   `xml:"value"`
	}

	var v Something

	data := `
	<something>
		<name> toto </name>
		<value type="item"> my item </value>
		<value type="other"> my other value </value>
	</something>
	`
	err := xml.Unmarshal([]byte(data), &v)
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}

	fmt.Println(v)
}

在解码后,你可以根据需要处理切片,提取值并将它们放入特定的字段中。

英文:

I do not think it is possible to directly map a list of items discriminated by an attribute value to specific fields. You need to map it to a slice, like in the following example (Items slice):

package main

import (
	&quot;encoding/xml&quot;
	&quot;fmt&quot;
)

func main() {

	type Item struct {
		Type string `xml:&quot;type,attr&quot;`
		Value string `xml:&quot;,chardata&quot;`
	}

	type Something struct {
		XMLName xml.Name `xml:&quot;something&quot;`
		Name string `xml:&quot;name&quot;`
		Items []Item `xml:&quot;value&quot;`
	}

	var v Something

	data := `
	&lt;something&gt;
		&lt;name&gt; toto &lt;/name&gt;
 		&lt;value type=&quot;item&quot;&gt; my item &lt;/value&gt;
 		&lt;value type=&quot;other&quot;&gt; my other value &lt;/value&gt;
	&lt;/something&gt;
	`
	err := xml.Unmarshal([]byte(data), &amp;v)
	if err != nil {
		fmt.Printf(&quot;error: %v&quot;, err)
		return
	}

	fmt.Println(v)
}

Up to you to process the slice after the decoding to extract the values and put them in specific fields if needed.

huangapple
  • 本文由 发表于 2015年2月4日 09:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/28311908.html
匿名

发表评论

匿名网友

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

确定