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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?