gpt4 book ai didi

xml - 使用属性解码 xml 标签

转载 作者:行者123 更新时间:2023-12-03 10:07:35 24 4
gpt4 key购买 nike

我正在尝试从 XML 中提取一些数据。 XML 标记具有属性和值。我只对值而不是属性感兴趣。这是我正在尝试的:

package main

import (
"encoding/xml"
"fmt"
)

type Data struct {
Info Information `xml:"Reference"`
}

type Information struct {
Uid string `xml:"uid,attr"`
Name string `xml:",chardata"`
}

func main() {
str := `<?xml version="1.0" encoding="utf-8"?>
<Reference uid="123">TestName</Reference>`

var testData Data

_ = xml.Unmarshal([]byte(str), &testData)

fmt.Println("Name is ", testData.Info.Name)
fmt.Println("uid is ", testData.Info.Uid)

return
}

最佳答案

您的源 XML 包含一个 <Reference>元素(和 不是 另一个元素内的元素),所以用一个简单的 struct 对其进行建模(和 不是 结构在另一个结构中):

type Information struct {
Uid string `xml:"uid,attr"`
Name string `xml:",chardata"`
}
并将其解码为该结构的值:
var testData Information

err := xml.Unmarshal([]byte(str), &testData)
fmt.Println(err)

fmt.Println("Name is ", testData.Name)
fmt.Println("uid is ", testData.Uid)
这将输出(在 Go Playground 上尝试):
<nil>
Name is TestName
uid is 123

关于xml - 使用属性解码 xml 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65311030/

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