Using a Perl replace statement (s//) I’d like to modify some XML by adding an attribute to some items if missing. Here’s an example :
...
<car color="red" owner="john">...</car>
<car color="green" age="3">...</car>
...
Let’s say I’d like to add a default owner to ownlerless cars. I tried the following without success :
s/(<car[^>]*)(?!owner="[^"]*")(.*>)|$1 owner="steve"$2/iUg
Any help appreciated.
While you may be able to get away with a regex, an XML parser is always recommended.
Perl/CPAN offerings include:
XML::SimpleTreats your XML document like a Perl data structure
XML::ParserAn old-timer
XML::SAXFor SAX parsing needs
XML::TwigFor memory-efficient processing of XML documents in chunks
XML::LibXMLMy personal favorite