Golang编组动态XML元素名称

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

Golang marshal dynamic xml element name

问题

XML文件由两个元素组成。这些元素具有相同的结构,除了一个元素名称不同。我尝试设置XMLName属性的值,但没有成功。

XML:

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


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

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

type Person struct {
    XMLName string `xml:"???"` // 如何使其动态?
    e1 string `xml:"ELEM1"`
    e2 string `xml:"ELEM2"`
    e3 string `xml:"ELEM3"`
    e4 string `xml:"ELEM4"`
}
英文:

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:

&lt;!-- first element --&gt;
&lt;PERSON&gt;
  &lt;ELEM1&gt;...&lt;/ELEM1&gt;
  &lt;ELEM2&gt;...&lt;/ELEM2&gt;
  &lt;ELEM3&gt;...&lt;/ELEM3&gt;
  &lt;ELEM4&gt;...&lt;/ELEM4&gt;
&lt;/PERSON&gt;


&lt;!-- second element --&gt;
&lt;SENDER&gt;
  &lt;ELEM1&gt;...&lt;/ELEM1&gt;
  &lt;ELEM2&gt;...&lt;/ELEM2&gt;
  &lt;ELEM3&gt;...&lt;/ELEM3&gt;
  &lt;ELEM4&gt;...&lt;/ELEM4&gt;
&lt;/SENDER&gt;

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

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

答案1

得分: 10

文档中,它说XMLName字段必须是xml.Name类型。

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

通过xml.NameLocal字段设置元素名称:

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

(另外,为了将其包含在XML输出中,E1 - E4必须是可导出的)。

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

英文:

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

type Person struct {
    XMLName xml.Name
    E1 string `xml:&quot;ELEM1&quot;`
    // ...
}

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

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

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

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

答案2

得分: 3

我找到了一个更简洁的解决方案,你只需要像这样为XMLName字段设置结构标签:

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

I found a lighter solution for this case where you only need to set the struct tag for XMLName field like this:

type Person struct {
    XMLName xml.Name `xml:&quot;Person&quot;`
    E1 string        `xml:&quot;ELEM1&quot;`
    // ...
}

huangapple
  • 本文由 发表于 2014年11月11日 22:40:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/26867417.html
匿名

发表评论

匿名网友

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

确定