I do not know XML::LibXML, so I don't really understand what your code is doing, and I don't know exactly where you should filter the output. But it should be right after the output is completely generated and before it is printed out.