Golang marshal动态xml元素名称 [英] Golang marshal dynamic xml element name

查看:926
本文介绍了Golang marshal动态xml元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

xml文件由两个元素组成。除一个元素名称外,这些元素具有相同的结构。我尝试为XMLName属性设置一个值,但这不起作用。



Xml:



 <! - 第一个元素 - > 
< PERSON>
< ELEM1> ...< / ELEM1>
< ELEM2> ...< / ELEM2>
< ELEM3> ...< / ELEM3>
< ELEM4> ...< / ELEM4>
< / PERSON>


<! - 第二个元素 - >
< SENDER>
< ELEM1> ...< / ELEM1>
< ELEM2> ...< / ELEM2>
< ELEM3> ...< / ELEM3>
< ELEM4> ...< / ELEM4>
< / SENDER>

是否可以定义一个结构,以使元素名称是动态的?

 类型Person结构{
XMLName字符串`xml:???`//如何使这个动态?
e1 string`xml:ELEM1`
e2 string`xml:ELEM2`
e3 string`xml:ELEM3`
e4 string`xml:ELEM4 `
}


解决方案

href =http://golang.org/pkg/encoding/xml/#Marshal>文档,它表示 XMLName 字段必须是类型的 xml.Name

 类型Person结构{
XMLName xml.Name
E1字符串`xml:ELEM1`
// ...
}

通过<$ xml.Name 本地字段:

  person:= Person {
XMLName:xml.Name {Local:Person},
// ...
}

(此外,必须导出E1-E4才能包含在XML输出中)。



Playground示例: http://play.golang.org/p/bzSutFF9Bo


The xml file consists of two elements. Those elements have the same structure except for one element name. I tried to set a value to the XMLName property, but that didn't work.

Xml:

<!-- first element -->
<PERSON>
  <ELEM1>...</ELEM1>
  <ELEM2>...</ELEM2>
  <ELEM3>...</ELEM3>
  <ELEM4>...</ELEM4>
</PERSON>


<!-- second element -->
<SENDER>
  <ELEM1>...</ELEM1>
  <ELEM2>...</ELEM2>
  <ELEM3>...</ELEM3>
  <ELEM4>...</ELEM4>
</SENDER>

Is it possible to define a struct such that the element name is dynamic?

type Person struct {
    XMLName string `xml:"???"` // How make this dynamic?
    e1 string `xml:"ELEM1"`
    e2 string `xml:"ELEM2"`
    e3 string `xml:"ELEM3"`
    e4 string `xml:"ELEM4"`
}

解决方案

In the documentation, it says that the XMLName field must be of type xml.Name.

type Person struct {
    XMLName xml.Name
    E1 string `xml:"ELEM1"`
    // ...
}

Set the element name via the Local field of xml.Name:

person := Person { 
    XMLName: xml.Name { Local: "Person" },
    // ...
}

(Also, E1 - E4 must be exported in order to be included in the XML output).

Playground example: http://play.golang.org/p/bzSutFF9Bo

这篇关于Golang marshal动态xml元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆