This question is all over the internet but all the examples I see do not take into account my apparently unique circumstances. Here is an excerpt from my XML:
<message type="error" from="Realtime" timestamp="Mon Nov 24 19:28:55 2014"> Could not receive from Loader </message>
<message type="warning" from="Dcd_Mux" timestamp="Mon Dec 1 02:31:18 2014"> Could not connect to Dcd </message>
Instead of having several levels of nodes, I just have several attributes on a message node. I want to be able to filter out nodes based on an argument to my Perl script. For example: If I wanted to filter out all messages with type="error", and I was using an XML that only had the 2 lines from above, my output would only be the warning message from above. Output shown here:
<message type="warning" from="Dcd_Mux" timestamp="Mon Dec 1 02:31:18 2014"> Could not connect to Dcd </message>
I need some direction on how to begin opening the XML, looping through the entire thing, and removing any nodes that have attributes that match my filter. I'm interested in using LibXML to get this done.
This solution is a variation on the one from Hunter McMillen, and is here largely to illustrate what I meant by "looks like a Java program written in Perl".
The parameter validation is part of it and, while I have reduced it to a simple count check, I would not normally write anything at all. It is of doubtful worth as the question is about how to process the data, and any such trimmings depend on who will be using the program and how often.
I have chosen to serialize the output and print it to
STDOUT
, as it is often more useful to be able to redirect output as required on the command line.I recognized what I thought was a Java-style approach by the attention to verification and general "protecting me from myself". I don't believe that adding a label and using it in
next
is at all helpful, especially with such a short loop.output
It could look something like this using
XML::LibXML
:I use XML::LibXML as my XML parser.
There's two elements to your problem - first building a filter criteria, and the selecting or deleting elements based on it.
In particular - mixing 'add' and 'remove' can be quite difficult, because deciding what to do if they don't apply or contradict can be rather annoying.
Anyway, I'm offering
XML::Twig
despite that not being precisely what you've asked for - because I've used it a fair bit, and haven't really touched LibXML.