|Perl Monk, Perl Meditation|
Re: Some questions from beginning user of XML::LibXML and XPathby Jim (Curate)
|on Oct 16, 2012 at 16:27 UTC||Need Help??|
I would have used regular expression pattern matching for this seemingly trivial text substitution (insertion) problem. The formatting of the XML is quite regular and straightforward. Both the string you're matching and the string you're replacing (enhancing) it with are distinct and uncomplicated. You say you "had a hell of a time getting XPath to work." I wouldn't have had the patience to try.
You're explicitly handling both the input text and the output text as binary data rather than as Unicode text? Why?
Here's the operation reduced to a Unicode-conformant one-liner:
Modify the anchoring regular expression patterns to taste.
Doing it this way avoids the needless and undesirable reordering of the attributes of the <Project> element—and a lot of other XML folderol besides. It also handles the input and output properly as Unicode text rather than as binary data and leaves the existing UTF-8 byte order mark intact.
Modifying this one-liner to support file and folder name globs (wildcards) is left as an exercise for the reader.
UPDATE: With modern versions of Perl, you can use the special look-behind assertion \K to obviate the separate pattern match used to anchor the substitution (insertion) to just those lines that have <OutDir> and <IntDir> elements on them.