duanchen9594 2018-08-02 08:27
浏览 94
已采纳

如何使用go检查XML文件中是否存在标签?

I don't know the tags that are present in the XML file. I'd like to know whether a certain tag exists. For example, suppose the file is like this:

<?xml version='1.1' encoding='UTF-8'?>
<tag1>
    <tag2></tag2>
</tag1>
<tag3/>

Here I'd like to check whether tag2 exists. The only way to parse XML files using go is by defining structs, but for that, I'll have to know what tags are present in the file, which I don't.

  • 写回答

2条回答 默认 最新

  • dongyan2267 2018-08-02 09:11
    关注

    You may use event-driven XML parsing. Create an xml.Decoder using xml.NewDecoder(), and parse the content of the XML by calling Decoder.Token() repeatedly (in a loop).

    You can check if a token is a start element using a type assertion, checking for the xml.StartElement type. If the assertion succeeds, you can check the name of the element if it matches the one you're looking for.

    This is how it could look like:

    func checkTag(src, tag string) (bool, error) {
        decoder := xml.NewDecoder(strings.NewReader(src))
    
        for {
            t, err := decoder.Token()
            if err != nil {
                if err == io.EOF {
                    return false, nil
                }
                return false, err
            }
            if se, ok := t.(xml.StartElement); ok {
                if se.Name.Local == tag {
                    return true, nil
                }
            }
        }
    }
    

    Testing it:

    func main() {
        fmt.Println(checkTag(src, "tag2"))
        fmt.Println(checkTag(src, "tagX"))
    }
    
    const src = `<?xml version='1.0' encoding='UTF-8'?>
    <tag1>
        <tag2></tag2>
    </tag1>
    <tag3/>`
    

    Output (try it on the Go Playground):

    true <nil>
    false <nil>
    

    As you can see, tag2 was properly found in the source XML, and tagX was properly not found.

    See related question: Unmarshalling heterogeneous list of XML elements in Go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?