【问题标题】:How to validate a XML如何验证 XML
【发布时间】:2019-04-27 19:07:49
【问题描述】:

我是 Go 新手,我正在尝试验证 XML,但我做不到。以下是我尝试过的,但它不起作用。有什么办法吗。

func ParseXml(xml_path string) {
    xmlFile, err := os.Open(xml_path)
    if err != nil {
        panic(err)
    } 
    // defer the closing of our xmlFile so that we can parse it later on
    defer xmlFile.Close()
    // read our opened xmlFile1 as a byte array. here I am checking if the file is valid or not
    byteValue, err := ioutil.ReadAll(xmlFile)
    if err != nil {
        panic(fmt.Sprintf("%s file reading failed \n",xml_path))
    } 
}

虽然我传递了一个无效的 XML 文件,但之后我并没有感到恐慌

    byteValue, err := ioutil.ReadAll(xmlFile)

【问题讨论】:

  • 请包括所有相关的错误信息。如果您没有收到错误,您期望的输出是什么,您会看到什么?

标签: xml validation go xml-parsing


【解决方案1】:

您的代码未验证 XML 语法。无论文件做什么,您的代码都会读取文件。验证 XML 的最简单方法是使用 xml 包。

func IsValidXML(data []byte) bool {
    return xml.Unmarshal(data, new(interface{})) == nil
}

所以关于你的代码,它应该是这样的:

func ParseXml(xml_path string) {
    xmlFile, err := os.Open(xml_path)
    if err != nil {
        panic(err)
    } 
    // defer the closing of our xmlFile so that we can parse it later on
    defer xmlFile.Close()
    // read our opened xmlFile1 as a byte array. here I am checking if the file is valid or not
    byteValue, err := ioutil.ReadAll(xmlFile)
    if err != nil {
        panic(fmt.Sprintf("%s file reading failed \n",xml_path))
    }

    if !IsValidXML(byteValue) {
        panic("Invalid XML has been input")
    }
}

有关xml.Unmarshal 的文档,请访问https://golang.org/pkg/encoding/xml/#Unmarshal

【讨论】:

  • 我认为上面的函数IsValidXML()有错误;应该是==
  • 请注意,这至多是检查文档是否“格式正确”的 XML。验证一般是指检查文档是否符合模式的过程。
  • @EB2127 是的,我的条件有问题 ngl lol
【解决方案2】:

遗憾的是,您不能只使用xml.Unmarshal,因为这会在第一个元素关闭后停止解析。示例:

func IsValid(s string) bool {
    return xml.Unmarshal([]byte(s), new(interface{})) == nil
}

func main() {
    // Prints "true".
    fmt.Println(IsValid("<foo></foo><<<<<<<"))
}

但是,您可以重复解码元素,直到出现非 io.EOF 错误:

func IsValid(input string) bool {
    decoder := xml.NewDecoder(strings.NewReader(input))
    for {
        err := decoder.Decode(new(interface{}))
        if err != nil {
            return err == io.EOF
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2010-12-05
    • 2011-01-26
    • 2016-12-18
    • 2016-04-08
    • 2013-06-16
    相关资源
    最近更新 更多