gpt4 book ai didi

go - 如何在 Go xml 结构标记中表示替代项

转载 作者:IT王子 更新时间:2023-10-29 01:45:24 26 4
gpt4 key购买 nike

我正在尝试编写一组适当的结构标记来解析 XML version of UCUM .以下是 unit 标记的两个示例:

<unit Code="deg" CODE="DEG" isMetric="no" class="iso1000">
<name>degree</name>
<printSymbol>&#176;</printSymbol>
<property>plane angle</property>
<value Unit="[pi].rad/360" UNIT="[PI].RAD/360" value="2">2</value>
</unit>

<unit Code="[degF]" CODE="[DEGF]" isMetric="no" isSpecial="yes" class="heat">
<name>degree Fahrenheit</name>
<printSymbol>&#176;F</printSymbol>
<property>temperature</property>
<value Unit="degf(5 K/9)" UNIT="DEGF(5 K/9)">
<function name="degF" value="5" Unit="K/9"/>
</value>
</unit>

棘手的部分是 value 标签的内容,它可以是一个字符串(我用字符串属性表示)或一个函数(它需要一个自己的结构).到目前为止,这是我得到的:

type Unit struct {
Code string `xml:Code,attr`
CodeCaps string `xml:CODE,attr`
IsMetric bool `xml:isMetric,attr,omitempty`
IsSpecial bool `xml:isEmptySpecial,attr,omitempty`
Class string `xml:class,attr`
Name string `xml:name`
PrintSymbol string `xml:printSymbol,chardata`
DimensionTypeKey string `xml:property,chardata`
Value struct {
Unit string `xml:Unit,attr`
UnitCaps string `xml:UNIT,attr`
Value string `xml:Value,attr`
PrintValue string `xml:,chardata`
Function struct { ... }
} `xml:value`
}

如何用结构标签准确描述这个 XML?

最佳答案

您的代码几乎可以正常工作; here's the fixed version .

基本上您需要进行以下调整:

  • 在结构标签中,值——xml: 之后的位前缀——必须用双引号括起来,像这样:

    `xml:"foo,attr"`
  • 无需指定 ,chardata当您只想获取元素标签之间的任何内容时使用 bit。

  • 提取<function>元素只是为 is 提供一个数据类型:解析器将在它存在或不存在时提取它。

    判断是否有<function>与否,您可以检查 PrintValue 的值字段:如果不是全空白,则没有 <function>元素;否则有。

    或者,定义一个单独的 struct用于解码此元素的数据类型,并将其字段定义为指向该类型的指针,喜欢在

    type Function struct { ... }
    ...
    Function *Function `xml:"function"`

    这样,如果没有<function> element 该字段的值将为 nil ,否则它将指向堆分配的 Function实例。

关于go - 如何在 Go xml 结构标记中表示替代项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36015394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com