XML/XPath on the commandline (EvE)

April 28, 2016

I saw a bunch of strange things (as in shell scripts) during my life as a system administrator. After leaving that field of expertise and doing something else I was hired by someone to check their shell script collection…

I still see scripts on the commandline that use some weird regular expressions to get certain values from XML files.

It’s so much easier to use xpath on the commandline to extract values from a XML file that comes from a REST api.

Let’s take the EVE Online api as an example. The EVE online game provides an API that you can abuse to find out about the number of players playing EVE right now.

    GET https://api.eveonline.com/server/ServerStatus.xml.aspx
    # result
    <eveapi version="2">
      <currentTime>2016-05-04 06:20:42</currentTime>
      <result>
        <serverOpen>True</serverOpen>
        <onlinePlayers>19014</onlinePlayers>
      </result>
      <cachedUntil>2016-05-04 13:20:58</cachedUntil>
    </eveapi>

By using curl you can query the XMLRPC interface directly and you can pipe the output into the command xmllint. The tool xmllint is part of the libxml2 software. The correct XPATH command will parse the file and return the node to you. As you are just interested in the number you use the number function to return the value only.

    $ curl -sL https://api.eveonline.com/server/ServerStatus.xml.aspx | \
      xmllint --xpath 'number(//onlinePlayers)' -

    # result
    20052

Well, that looks way better than the old grep things! Be aware there are some pitfalls if you use that toolchain on Windows. Check your path - Windows (mine did) shipped with it’s own version of xmllint which came from a dev toolkit. Unfortunately, it’s an old version that doesn’t understand the --xpath flag.

References

Finding the binary tools is hard. Here are some helpful links.

Comments

comments powered by Disqus