使用Go解析XML时,无法从单个标签中获取值。

huangapple go评论91阅读模式
英文:

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:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;boolean xmlns=&quot;http://foo.com.BARRSD/&quot;&gt;true&lt;/boolean&gt;

I first tried defining this struct to use with the xml.Unmarshal method:

type Authenticate struct {
	Boolean bool `xml:&quot;boolean&quot;`
}

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:

&lt;boolean&gt;true&lt;/boolean&gt;

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:

&lt;authenticate&gt;
	&lt;boolean xmlns=&quot;http://foo.com.BARRSD/&quot;&gt;true&lt;/boolean&gt;
&lt;/authenticate&gt;

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:&quot;,chardata&quot;`
}

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), &amp;b); err != nil {
	panic(err)
}

Try this one on the Go Playground.

huangapple
  • 本文由 发表于 2021年9月1日 04:26:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/69004955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定