如何验证XML

时间:2018-11-26 06:53:10

标签: xml validation go xml-parsing

我是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)

2 个答案:

答案 0 :(得分:0)

您的代码未验证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

答案 1 :(得分:0)

遗憾的是,您不能只使用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
        }
    }
}