gpt4 book ai didi

XML 通过字段名称中的索引解码动态响应

转载 作者:行者123 更新时间:2023-12-03 02:23:32 24 4
gpt4 key购买 nike

我正在尝试解码“动态”XML 响应,但我不确定如何处理它。服务器响应相当大的响应,所以我不想两次解析响应。 XML 如下所示:

...
<nic_cnt>2</nic_cnt>
<ifindex1>eno1</ifindex1>
<ifindex2>eno2</ifindex2>
...

因此,nic_cnt 字段定义了 ifindex 发生的次数。由于我不知道 ifindex 会发生多少次,因此我无法静态定义解码响应所需的结构字段。

最佳答案

您可以使用 ,any 的 slice XML标签选项告诉 encoding/xml 包以将任何 XML 标记放入其中。这记录在 xml.Unmarshal() :

If the XML element contains a sub-element that hasn't matched any
of the above rules and the struct has a field with tag ",any",
unmarshal maps the sub-element to that struct field.

对于<ifindexXX>标签使用另一个包含 XMLName 的结构类型字段 xml.Name 因此,如果您需要仅过滤以 ifindex 开头的字段,则实际的字段名称将可用。 .

让我们解析以下 XML:

<root>
<nic_cnt>2</nic_cnt>
<ifindex1>eno1</ifindex1>
<ifindex2>eno2</ifindex2>
</root>

我们可以用以下方式对其进行建模:

type Root struct {
NicCnt int `xml:"nic_cnt"`
Entries []Entry `xml:",any"`
}

type Entry struct {
XMLName xml.Name
Value string `xml:",innerxml"`
}

解析它的示例代码:

var root Root
if err := xml.Unmarshal([]byte(src), &root); err != nil {
panic(err)
}
fmt.Printf("%+v", root)

输出(在 Go Playground 上尝试):

{NicCnt:2 Entries:[
{XMLName:{Space: Local:ifindex1} Value:eno1}
{XMLName:{Space: Local:ifindex2} Value:eno2}]}

请注意Root.Entries还将包含其他未映射的 XML 标记。如果您只关心以 ifindex 开头的标签,这就是“过滤”它们的方法:

for _, e := range root.Entries {
if strings.HasPrefix(e.XMLName.Local, "ifindex") {
fmt.Println(e.XMLName.Local, ":", e.Value)
}
}

如果 XML 还包含附加标签:

<other>something else</other>

输出将是(在 Go Playground 上尝试这个):

{NicCnt:2 Entries:[
{XMLName:{Space: Local:ifindex1} Value:eno1}
{XMLName:{Space: Local:ifindex2} Value:eno2}
{XMLName:{Space: Local:other} Value:something else}]}
ifindex1 : eno1
ifindex2 : eno2

关于XML 通过字段名称中的索引解码动态响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58182643/

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