Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return array with XPath?

I was wondering if XPath could return an array of value.

I have someting like this :

<Cities>
    <City>Paris</City>
    <City>Lyon</City>
    <City>Marseille</City>
</Cities>

And I'd like to get an array of this form ['Paris', 'Lyon', 'Marseille'].

I am using the xpath UNIX utility.

Any idea ?

like image 367
Spredzy Avatar asked Feb 23 '11 14:02

Spredzy


1 Answers

In addition to post-processing the output of:

xpath -q -e '//City/text()' inputfile

which is:

Paris
Lyon
Marseille

in any number of ways, including:

xpath -q -e '//City/text()' inputfile |
    awk 'BEGIN {sq = "\047"; OFS = sq "," sq}
         {a[$1] = NR}
         END {
             printf "[" sq; 
             for (i in a) {
                 printf "%s%s", d, i; d = OFS};
             print sq "]"
         }'

which gives the output:

['Lyon','Marseille','Paris']

you can use my modified version of xpath. Since it's a simple Perl script, I modified it so you have more control over the formatting of the output. With my version, you can do:

xpath -q -b "[" -p "'" -i "," -s "'" -a "]"$'\n' -e '//City/text()'

to get the desired output. Here is the usage message:

Usage:
xpath [options] -e query [-e query...] [filename...]

        If no filenames are given, supply XML on STDIN.
        You must provide at least one query. Each supplementary
        query is done in order, the previous query giving the
        context of the next one.

        Options:

        -q quiet        Only output the resulting PATH
        -b before       use before instead of nothing.
        -p prefix       use prefix instead of nothing.
        -s suffix       use suffix instead of linefeed.
        -i infix        use infix instead of nothing.
        -a after        use after instead of nothing.

You can download my version here.

like image 100
Dennis Williamson Avatar answered Oct 21 '22 14:10

Dennis Williamson