英文:
Unmarshalling XML from result of xml.Marshal()
问题
我有一个小的struct
,我想使用encoding/xml
包进行编组和解组:
type Point struct {
X, Y int
z int // 未导出字段
Names []string
}
当我使用encoding/json
包时,编码和解码都正常工作。
但是当我使用encoding/xml
包时,只有xml.Marshal()
正常工作,xml.Unmarshal()
返回一个错误:
invalid character '<' looking for beginning of value
这是我用于XML的代码:
p := Point{1, 2, 3, []string{"Bob", "Alice"}}
data, err := xml.Marshal(p)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("XML:", string(data))
var pXml Point
err = json.Unmarshal(data, &pXml)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Unmarshalled XML:", pXml)
为什么会出现这个错误,如何解组xml.Marshal()
返回的XML输出?
你可以在Go Playground上尝试完整可运行的应用程序。
应用程序的输出:
Input: {1 2 3 [Bob Alice]}
JSON: {"X":1,"Y":2,"Names":["Bob","Alice"]}
Unmarshalled JSON: {1 2 0 [Bob Alice]}
XML: <Point><X>1</X><Y>2</Y><Names>Bob</Names><Names>Alice</Names></Point>
Error: invalid character '<' looking for beginning of value
Unmarshalled XML: {0 0 0 []}
英文:
I have a small struct
which I want to marshal and unmarshal using the encoding/xml
package:
type Point struct {
X, Y int
z int // unexported
Names []string
}
The encoding/decoding works fine when I use the encoding/json
package.
But when I use the encoding/xml
package, only the xml.Marshal()
works, the xml.Unmarshal()
returns an error:
invalid character '<' looking for beginning of value
This is how I do it for XML:
p := Point{1, 2, 3, []string{"Bob", "Alice"}}
data, err := xml.Marshal(p)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("XML:", string(data))
var pXml Point
err = json.Unmarshal(data, &pXml)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("Unmarshalled XML:", pXml)
Why do I get this error and how can I unmarshal the XML output returned by xml.Marshal()
?
Here is the complete, runnable application on the Go Playground to try out.
Output of the application:
Input: {1 2 3 [Bob Alice]}
JSON: {"X":1,"Y":2,"Names":["Bob","Alice"]}
Unmarshalled JSON: {1 2 0 [Bob Alice]}
XML: <Point><X>1</X><Y>2</Y><Names>Bob</Names><Names>Alice</Names></Point>
Error: invalid character '<' looking for beginning of value
Unmarshalled XML: {0 0 0 []}
答案1
得分: 3
你正在尝试将 XML 解组为 JSON。首先,你执行以下操作:
data, err := xml.Marshal(p)
然后执行以下操作:
err = json.Unmarshal(data, &pXml)
你代码中的第 46 行应该是:
err = xml.Unmarshal(data, &pXml)
英文:
You are trying to unmarshal XML as if it's JSON. First you do
data, err := xml.Marshal(p)
and then
err = json.Unmarshal(data, &pXml)
Line 46 in your code should be
err = xml.Unmarshal(data, &pXml)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论