Using Perl in XSH
Perl is integrated much better with the recently released XSH2 than with the old XSH1. To invoke Perl code, simply surround it with braces (the "{" and "}" characters). Open the saved file from the previous section by typing:
open "new_filename.xml"
Now try the following command:
foreach my $pubdate in //publication-date { my $year; my $month;
my $day; perl { literal($pubdate) =~ /(\d{4})-(\d\d)-(\d\d)/; $year = $1; $month = $2; $day = $3; }; remove
$pubdate/text(); insert chunk "<year>${year}</year><month>${month}</month><day>${day}</day>
" into $pubdate; }
You unfortunately have to type it all on one line. XSH lets you break things over multiple lines, but only in batch scripts. The above command breaks apart the publication date into three subfields, as follows:
/> ls //books/book/publication-date
<publication-date>
<year>1987</year>
<month>03</month>
<day>12</day>
</publication-date>
<publication-date>
<year>2003</year>
<month>09</month>
<day>30</day>
</publication-date>
<publication-date>
<year>1998</year>
<month>08</month>
<day>01</day>
</publication-date>
<publication-date>
<year>2003</year>
<month>02</month>
<day>01</day>
</publication-date>
<publication-date>
<year>1983</year>
<month>01</month>
<day>01</day>
</publication-date>
Found 5 node(s).
Other Uses of XSH
XSH accepts input from any stream, meaning you can use it as a batch-processing tool as well as an interactive shell. Bash and other Unix shells operate both interactively and in batch mode, so the dual mode operation is natural for anyone who uses Unix tools. Although beyond the scope of this article, batch operation of XSH can help you solve problems that would be difficult or convoluted with just XSLT, and since it simply involves feeding commands to XSH from a file instead of standard input, the transition is simple. Just type your commands into a text editor and then feed that text file to XSH.
If you work with a substantial amount of XML, tools for simple and quick query and manipulation of XML trees are essential. Now that you know what XSH does and how it can help you, it should be a valuable tool in your toolbox.