Search code examples
xmlbashxpathxmlstarlet

xmlstarlet always count 0


In order to realize a script to import into my db, I would like to count the number of iteration of a node in an xml file. I'm tried to use xmlstarlet, but each time he is returning 0 as answer...

Here is a sample of my XML file :

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> 
<global xmlns="http://www.xxxxxxxxxxx">
     <place geoAccuracy="0" geoStatus="0" geoLatDeg="0.0" geoLongDeg="0.0" id="123">
         <name>XXXXXX</name>
         <postalcode>12345</postalcode>
         <city>city</city>
         <country>country</country>
     </place>
     <place geoAccuracy="0" geoStatus="0" geoLatDeg="0.0" geoLongDeg="0.0" id="123">
         <name>XXXXXX</name>
         <postalcode>12345</postalcode>
         <city>city</city>
         <country>country</country>
    </place>

In my bash, I did this :

#!/bin/bash
FILE="places.xml" RESULT=$(xmlstarlet sel -t -v "count(//place)" $FILE)
echo $RESULT

Each time, it returns 0 as a result... I've tried different XPaths like "//global/place" or "/place" but the result is the same...

Does any one has any idea on how to resolve it ? I'm a using an Ubuntu server 14.04LTS.


Solution

  • @O.R.Mapper is correct: You have to specify the namespace when using xmlstarlet:

     xmlstarlet sel -N q="http://www.xxxxxxxxxxx" -t -v 'count(//q:place)' "$FILE"
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                ^^
    

    works for me (returns 2, provided I add </global> to the end of the test sample you provided).

    The q is the name you will use to refer to the namespace, and the http...x is the xmlns value from your XML file. Then each tag name has q: added to the front of it to specify the namespace. Instead of q, you can use whatever ID you want to refer to the namespace — the URL is what defines the namespace, not the reference.

    From the docs.