当前位置 : 主页 > 网页制作 > xml >

xml-parsing – Go中的DRY结构标记

来源:互联网 收集:自由互联 发布时间:2021-06-13
我正在解析 XML,并且至多文档的每个级别都有一个描述. 这是一个玩具示例: obj descriptionouter object/description subobjA descriptionfirst kind of subobject/description foosome goop/foo /subobjA subobjB descriptio
我正在解析 XML,并且至多文档的每个级别都有一个描述.

这是一个玩具示例:

<obj>
    <description>outer object</description>
    <subobjA>
        <description>first kind of subobject</description>
        <foo>some goop</foo>
    </subobjA>
    <subobjB>
        <description>second kind of subobject</description>
        <bar>some other goop</bar>
    </subobjB>
</obj>

这意味着所涉及的每个结构都具有相同的Description成员,具有相同的标记`xml:“description,omitempty”`.

这是功能代码:http://play.golang.org/p/1-co6Qcm8d

我宁愿描述标签是DRY.要做的显而易见的事情是这样的:

type Description string `xml:"description,omitempty"`

然后使用整个类型描述.但是,只有struct成员才能拥有标记.请参阅http://play.golang.org/p/p83UrhrN4u,了解我想写的内容;它没有编译.

可以创建一个Description结构并重复嵌入它,但是在访问时会增加一个间接层.

还有另一种方法可以解决这个问题吗?

嵌入一​​个重新分解的描述结构(如您所建议的)是要走的路:

(Playground)

type describable struct{
    Description string `xml:"description"`
}

type subobjA struct {
    describable
    XMLName     xml.Name `xml:"subobjA"`
}

type subobjB struct {
    describable
    XMLName     xml.Name `xml:"subobjB"`
}

type obj struct {
    XMLName     xml.Name `xml:"obj"`
    A           subobjA
    B           subobjB
}

提到的间接层不存在.在该主题上引用the spec:

A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

所以你可以这样做:

err := xml.Unmarshal([]byte(sampleXml), &sampleObj)
fmt.Println(sampleObj.Description)
fmt.Println(sampleObj.A.Description)

sampleObj.describable.Description被提升为sampleObj.Description,因此这里没有进一步的间接层.

网友评论