英文:
Parsing XML with Go not able to get value from single tag
问题
这是我第一次尝试使用Go语言的xml包,所以我认为我可能漏掉了一些东西。我有一个来自遗留的Web服务的简单XML:
<?xml version="1.0" encoding="utf-8"?>
<boolean xmlns="http://foo.com.BARRSD/">true</boolean>
我首先尝试定义以下结构体来与xml.Unmarshal方法一起使用:
type Authenticate struct {
Boolean bool `xml:"boolean"`
}
但我认为它无法"找到" boolean,所以Boolean中的结果值是初始化值false。我通过将Boolean重新定义为字符串进行了验证,结果只是一个空字符串。如果我进一步简化源XML,我得到相同的结果:
<boolean>true</boolean>
如何使用xml.Unmarshal解析出单个标签的值呢?
英文:
This is my first time trying to use the xml package for Go, so I assume I'm missing something. I have this simple XML from a legacy web service:
<?xml version="1.0" encoding="utf-8"?>
<boolean xmlns="http://foo.com.BARRSD/">true</boolean>
I first tried defining this struct to use with the xml.Unmarshal method:
type Authenticate struct {
Boolean bool `xml:"boolean"`
}
But I believe it's not able to "find" boolean so the resulting value in Boolean is the initialized value of false. And I sanity checked that was the case by redefining Boolean as a string, and that just resulted in an empty string. And I get the same results if I simplify the source XML even more:
<boolean>true</boolean>
How does one parse out the value of a single tag using xml.Unmarshal?
答案1
得分: 3
问题在于你的Go模型与XML结构不匹配。你的Go模型假设存在一个"authenticate"包装标签,并且它将匹配以下XML结构:
<authenticate>
<boolean xmlns="http://foo.com.BARRSD/">true</boolean>
</authenticate>
你可以在Go Playground上尝试一下。
由于你没有包装标签,你可以使用,chardata
XML标签选项来使用内部文本作为Boolean
字段:
type Authenticate struct {
Boolean bool `xml:",chardata"`
}
你可以在Go Playground上尝试一下。
还要注意,在这个特定的例子中,你也可以使用一个单独的bool
变量:
var b bool
if err := xml.Unmarshal([]byte(src), &b); err != nil {
panic(err)
}
你可以在Go Playground上尝试一下。
英文:
The problem is that your Go model does not match the XML structure. Your Go model assumes there's an "authenticate" wrapper tag, and it would would match this XML:
<authenticate>
<boolean xmlns="http://foo.com.BARRSD/">true</boolean>
</authenticate>
Try it on the Go Playground.
Since you don't have a wrapper tag, you may use the ,chardata
XML tag option to use the inner text for the Boolean
field:
type Authenticate struct {
Boolean bool `xml:",chardata"`
}
Try it on the Go Playground.
Also note that in this specific example you could also use a single bool
variable:
var b bool
if err := xml.Unmarshal([]byte(src), &b); err != nil {
panic(err)
}
Try this one on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论