Iterate through XML nodes with Lua

Viewed 98

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 Answers

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.

Related