Tagged: xml

Parsing XML from the command line

First apt-get install xmlstarlet. And let’s say we have this XML file:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">

We can use xmlstarlet sel to select elements. But first we need to tell it about the name space, so xmlstarlet sel -N x="http://www.opengis.net/kml/2.2".

Now let’s use -t -v to start using some XPath. In our case /x:kml/x:Document/x:name. So in full xmlstarlet sel -N x="http://www.opengis.net/kml/2.2" -t -v "/x:kml/x:Document/x:name" the_xml_file.xml. This will print:

xml unix

Java: Quick XML parsing using XPath and dom4j

If you download the dom4j jar, along with the jaxen jar, you can easily manipulate XML. I have versions 1.6 and 1.1 respectively. Add these to your Java build path in Eclipes.

Put an XML file, sample.xml in this case, in the same directory as the class you’ll be using

    <?xml version="1.0" encoding="UTF-8"?>
    <hello thing="yeah">World</hello>

Now for the code. The first bit is loading the XML. Creating the SAXReader, loading the resource into that, which will return a Document which you will use to get your XML data.

    InputStream lIs= Main.class.getClassLoader().getResourceAsStream("sample.xml");
    SAXReader lSr = new SAXReader();
    try {
       Document lDoc = lSr.read(lIs);
       List<Node> lS = lDoc.selectNodes("//hello");
       String s = lDoc.valueOf("/hello/@thing");
    } catch (DocumentException e) {

After the Document is created, you can use the XPath notation to grab the tags, the single hello in this case. And the notation to grab an attribute. See an XPath reference here: http://www.w3schools.com/xpath/xpath_syntax.asp

java java-domj4 xml

Page 1 of 1