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 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题