xml2lua给了我多个根节点

前端开发 2026-07-12

我正在尝试为一个Neovim插件使用xml2lua解析任意数量的XML文档(我使用的是一个定制打包版本,但用luarocks的包也能复现这个问题)。第一次尝试解析文档时,一切都按预期工作。第二次时,我得到的结构类似于:

{
    _type = 'ROOT',
    _children = {
        _type = 'ROOT',
        _children = { ---[[ ... ]] }
    }
}

我写了一个最小的示例来演示我的问题:

local xml2lua = require('xml2lua')
local handler = require('xmlhandler.dom')

local function count_root_nodes_in_dom(node)
    if type(node) ~= 'table' then -- trust me, I've seen functions spat at me already.
        return 0
    end

    local count = 0
    if node._type == 'ROOT' then
        count = count + 1
    end
    for _, child in ipairs(node._children) do
        count = count + count_root_nodes_in_dom(child)
    end
    return count
end

local function count_root_nodes()
    local parser = xml2lua.parser(handler)
    parser:parse('<xml></xml>')
    return count_root_nodes_in_dom(handler.root)
end

for _ = 1, 16 do
    print(count_root_nodes())
end

运行它时,我在控制台看到从1 到16的数字。

这是为什么?我已经尝试把 require 语句移到解析XML的函数内,以便每个 require 语句都在我需要解析的每个文档上执行一次,但我仍然看到这个问题。

解决方案

在重新使用 handle.root 之前,必须声明旧的节点树将不再被使用:

handler.root = nil

代码可以如下所示:

local function count_root_nodes()
    local parser = xml2lua.parser(handler)
    parser:parse('<xml></xml>')
    local n = count_root_nodes_in_dom(handler.root)
    handler.root = nil
    return n
end
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章