无上下文的XML结构标记化

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

Context-agnostic XML struct tagging

问题

我想要能够给我的结构体添加标签,而不需要知道它将嵌套到 XML 文档的哪个级别。换句话说,我希望能够这样写:

type Elem struct {
    Datum string `xml:"datum"`
}

并且它可以同时适用于以下两种情况:

<elem>
    <datum>Hello</datum>
</elem>

<list>
    <elem>
        <datum>Hello</datum>
    </elem>
</list>

然而,为了使后一个示例(尝试解码为 []Elem)正常工作,我需要使用标签 xml:"elem>datum",这会导致第一个示例解码错误。有没有办法在不知道结构体将如何嵌入的情况下定义 XML 标签?在这里可以看到一个简单的示例:

http://play.golang.org/p/LpI2vKFpNE

英文:

I would like to be able to tag my struct without it needing to know what level it will be nested into an XML document. In other words, I want to be able to write:

type Elem struct {
    Datum string `xml:&quot;datum&quot;`
}

And have it work for both

&lt;elem&gt;
    &lt;datum&gt;Hello&lt;/datum&gt;
&lt;/elem&gt;

And

&lt;list&gt;
    &lt;elem&gt;
        &lt;datum&gt;Hello&lt;/datum&gt;
    &lt;/elem&gt;
&lt;/list&gt;

However, in order for the latter example to work (when attempting to decode into a []Elem), I need to use the tag xml:&quot;elem&gt;datum&quot;, which decodes incorrectly for the first example. Is there a way for me to define an XML tag without knowing how the struct will be embedded? See here for a simple example:

http://play.golang.org/p/LpI2vKFpNE

答案1

得分: 1

一种解决方法是使用匿名结构体:

func Test2_DecodeList() {
    xmlData := "<list><elem><datum>Hello</datum></elem></list>"
    var list struct {
        Elems []Elem `xml:"elem"`
    }
    if err := xml.Unmarshal([]byte(xmlData), &list); err != nil {
        fatal("Test2:", err)
    }

    if err := expectEq(1, len(list.Elems)); err != nil {
        fatal("Test2:", err)
    }

    if err := expectEq("Hello", list.Elems[0].Datum); err != nil {
        fatal("Test2:", err)
    }
}

示例:http://play.golang.org/p/UyYoyGgL_K

英文:

One way to solve this is through the use of an anonymous struct:

func Test2_DecodeList() {
	xmlData := &quot;&lt;list&gt;&lt;elem&gt;&lt;datum&gt;Hello&lt;/datum&gt;&lt;/elem&gt;&lt;/list&gt;&quot;
	var list struct {
		Elems []Elem `xml:&quot;elem&quot;`
	}
	if err := xml.Unmarshal([]byte(xmlData), &amp;list); err != nil {
		fatal(&quot;Test2:&quot;, err)
	}

	if err := expectEq(1, len(list.Elems)); err != nil {
		fatal(&quot;Test2:&quot;, err)
	}

	if err := expectEq(&quot;Hello&quot;, list.Elems[0].Datum); err != nil {
		fatal(&quot;Test2:&quot;, err)
	}
}

Example: http://play.golang.org/p/UyYoyGgL_K

huangapple
  • 本文由 发表于 2014年10月22日 08:42:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/26498690.html
匿名

发表评论

匿名网友

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

确定