英文:
Xml Unmarshal failing
问题
我正在尝试将简单的 XML Schema 解组为结构体。如果在我的 XML 节点值中发现 
,似乎会失败。
读取 XML 文件会导致运行时错误。
读取 XML 字符串会导致丢失其他内容。
示例:http://play.golang.org/p/waNn_1NpD1
package main
import (
"encoding/xml"
"fmt"
)
const (
s = `<?xml version="1.0" encoding="UTF-8"?>
<feed>
<product>
<description>
TEST VALUE sdfsdfsdfsdfsd TEST VALUE sdfsdfsdfsdfsd TEST VALUE sdfsdfsdfsdfsd TEST VALUE sdfsdfsdfsdfsd &#031;
</description>
<sku>ABCDD!@#</sku>
</product>
</feed>`
)
type (
Feed struct {
XMLName xml.Name `xml:"feed"`
Product Product `xml:"product"`
}
Product struct {
XMLName xml.Name `xml:"product"`
Description string `xml:"description"`
SKU string `xml:"sku"`
}
)
func main() {
fmt.Println("Hello, playground")
b := []byte(s)
var feed Feed
xml.Unmarshal(b, &feed)
fmt.Println(feed.Product.Description)
fmt.Println(feed.Product.SKU)
}
希望对你有所帮助!
英文:
i am trying to Unmarshal simple Xml Schema to Struct. appears to be failing if i have &#031;
found in any of my Xml Node value.
Reading an Xml file leads to runtime error.
Reading an Xml string leads to missing all other
Sample : http://play.golang.org/p/waNn_1NpD1
package main
import (
"encoding/xml"
"fmt"
)
const (
s = `<?xml version="1.0" encoding="UTF-8"?>
<feed>
<product>
<description>
TEST VALUE sdfsdfsdfsdfsd TEST VALUE sdfsdfsdfsdfsd TEST VALUE sdfsdfsdfsdfsd TEST VALUE sdfsdfsdfsdfsd &#031;
</description>
<sku>ABCDD!@#</sku>
</product>
</feed>`
)
type (
Feed struct {
XMLName xml.Name `xml:"feed"`
Product Product `xml:"product"`
}
Product struct {
XMLName xml.Name `xml:"product"`
Description string `xml:"description"`
SKU string `xml:"sku"`
}
)
func main() {
fmt.Println("Hello, playground")
b := []byte(s)
var feed Feed
xml.Unmarshal(b, &feed)
fmt.Println(feed.Product.Description)
fmt.Println(feed.Product.SKU)
}
答案1
得分: 3
不要忽视你的错误
你的输入数据是无效的。
如果xml.Unmarshal
失败,它会返回一个error
。用以下代码替换你的调用:
if err != nil {
fmt.Println(err)
}
...显示:
XML语法错误,位于第6行:非法字符代码U+001F
从你的输入中移除&#031
就可以正常工作了。
<kbd>在Go Playground上查看</kbd>
英文:
Don't ignore your errors
Your input data is invalid.
xml.Unmarshal
returns an error
if it fails. Replacing your call with this:
if err != nil {
fmt.Println(err)
}
...shows:
XML syntax error on line 6: illegal character code U+001F
Removing the &#031
from your input makes it work.
<kbd>See it on the Go Playground</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论