【问题标题】:Decode XML string into struct将 XML 字符串解码为结构
【发布时间】:2023-02-09 13:16:09
【问题描述】:

我有以下 xml:

<DOC>
<SubGroup1>
    <Value1>ABC123</Value1>
    <Value2>ABC123</Value2>
    <Value3>ABC123</Value3>
    <Value4>ABC123</Value4>
</SubGroup1>
<SubGroup2>
    <TheTag MyTagAttr="ABC123">
        <Value1>ABC123</Value1>
        <Value2>ABC123</Value2>
        <Value3>ABC123</Value3>
        <Value4 MyTagAttr="ABC123">ABC123</Value4>
        <Value5>ABC123</Value5>
        <Value6>ABC123</Value6>
        <Value7>ABC123</Value7>
        <Value8>ABC123</Value8>
        <Value9>ABC123</Value9>
    </TheTag>
</SubGroup2>
</DOC>

我需要解码成这个结构:

type TheTag struct {
    XMLName xml.Name `xml:"SubGroup2>TheTag"`

    Value1  string  `xml:"Value1"`
    Value2  string  `xml:"Value2"`
}

但我无法将此子元素正确解码到结构中。

我收到以下错误:

error decoding message content: %!w(xml.UnmarshalError=expected element type <SubGroup2>TheTag> but have <DOC>)

我的代码在 Go Playgroud 上可用:https://go.dev/play/p/O688qTBARJm

提前致谢!

【问题讨论】:

    标签: go


    【解决方案1】:

    您可能应该移动标签。

    type TheTag struct {
      XMLName xml.Name `xml:"DOC"`
    
      Value1 string `xml:"SubGroup2>TheTag>Value1"`
      Value2 string `xml:"SubGroup2>TheTag>Value2"`
    }
    

    【讨论】:

    • 嗨 Stéphane,您的建议有效,谢谢!但是属性呢?你知道如何加载这些值吗?
    • @jsfelipearaujo,很抱歉你是个油嘴滑舌的人,但是你读过包文档了吗? SO 不是背诵它的服务,真的。特别是,请参阅the process of unmarshaling
    • @kostix,是的,我做到了。但是没有提到如何使用路径语法从子元素中读取属性。
    • @jsfelipearaujo,«如果 XML 元素有一个属性,其名称与结构字段名称匹配,并且关联标签包含“,attr”或形式为“name,attr”的结构字段标签中的显式名称,Unmarshal 记录属性值在那个领域。»然后«如果 XML 元素包含一个子元素,其名称与格式为“a”或“a>b>c”的标签的前缀相匹配,<…>»– 第一个解释 name,attr,第二个解释如何格式化 name 以引用嵌套元素。
    【解决方案2】:

    您可以使用库 github.com/clbanning/mxj

    xmlBytes = []byte("<DOC>...</DOC>")
    xmlStruct, err := mxj.NewMapXml(xmlBytes)
    if err != nil {
      // handle error
    }
    theTag, err := xmlStruct.ValuesForPath("DOC.SubGroup2.TheTag")
    if err != nil {
      // Do not exist "TheTag"
    }
    theTagInterface := theTag.(map[string]interface{})
    myTagAttr := theTagInterface["-MyTagAttr"].(string)
    
    val4, err := xmlStruct.ValuesForPath("DOC.SubGroup2.TheTag.Value4")
    if err != nil {
      // Do not exist "Value4"
    }
    theVal4Interface := val4.(map[string]interface{})
    myVal4Attr := theVal4Interface["-MyTagAttr"].(string)
    

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 2018-08-26
      • 2015-09-09
      • 2011-10-09
      • 1970-01-01
      • 2018-10-20
      • 2016-04-10
      • 1970-01-01
      • 2012-07-25
      相关资源
      最近更新 更多