Xml解组失败

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

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    
				</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  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    
                </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 &amp;#031 from your input makes it work.

<kbd>See it on the Go Playground</kbd>

huangapple
  • 本文由 发表于 2015年2月10日 05:08:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/28419396.html
匿名

发表评论

匿名网友

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

确定