使用Lua遍历XML节点 [英] Iterate through XML nodes with Lua

查看:65
本文介绍了使用Lua遍历XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历所有"FindMe"节点,但是我在模式匹配方面苦苦挣扎.这将用作另一个软件的插件,所以我试图避免使用解析库.

I'm trying to iterate through all the 'FindMe' nodes but I'm struggling with the pattern matching. This is going to be used as a plugin in another piece of software so I'm trying to avoid using a parsing library.

给出以下xml

<?xml version="1.0" encoding="utf-8"?>
<NodeA>
    <NodeB>
        <FindMe attr="1">
            <NodeC attr="1" />
        </FindMe>
        <FindMe attr="2">
            <NodeC attr="2" />
        </FindMe>
    </NodeB>
</NodeA>

当我尝试此操作时,它只会显示最后一场比赛

When I try this it only prints the last match

for k, _ in src:gmatch(".+(<FindMe .+</FindMe>).+") do
    print(k)
end

<FindMe attr="2">
    <NodeC attr="2" />
</FindMe>

当我尝试此操作时,它会将所有匹配的节点打印为一个结果

When I try this it prints all the matching nodes as one result

for k, _ in src:gmatch('<FindMe.+>.+</FindMe>') do 
    print(k) 
end

<FindMe attr="1">
    <NodeC attr="1" />
</FindMe>
<FindMe attr="2">
    <NodeC attr="2" />
</FindMe>

推荐答案

使用 .- 代替.+ ,这样 gmatch('< FindMe.+>.+</FindMe>')变为 gmatch('< FindMe .-> .-</FindMe>').使用-表示非贪婪搜索,因此它会获得直到匹配为止的最小字符数(而不是直到与贪婪搜索匹配的最大字符数).您还可以使用 gmatch('< FindMe [^>] +&.;-</FindMe>'),该效果应该相同.

Use .- instead of .+, such that gmatch('<FindMe.+>.+</FindMe>') becomes gmatch('<FindMe.->.-</FindMe>'). Using - implies non-greedy search, so it gets the smallest possible number of characters until the match (instead of the largest possible number of characters until the match with the greedy search). You can also use gmatch('<FindMe[^>]+>.-</FindMe>'), which should have the same effect.

这篇关于使用Lua遍历XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆