Iterate through XML nodes with Lua

核能气质少年 提交于 2021-01-27 14:20:21

问题


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.

Given the following 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>

回答1:


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.



来源:https://stackoverflow.com/questions/60751245/iterate-through-xml-nodes-with-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!