// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import org.apache.xpath.XPathAPI;

public class VariousXPath {
    public static void main(String[] args) throws Exception {
        String xml = "<demo>\r\n" +
                     "<title>bla bla</title>\r\n" +
                     "<item>\r\n" +
                     "<title>foo</title>\r\n" +
                     "<info url='foo.html'/>\r\n" +
                     "</item>\r\n" +
                     "<item>\r\n" +
                     "<title>bar</title>\r\n" +
                     "<info url='bar.html'/>\r\n" +
                     "</item>\r\n" +
                     "</demo>";
        System.out.println(xml);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(xml)));
        Node title = XPathAPI.selectSingleNode(doc.getDocumentElement(), "//demo/title/text()");
        System.out.println("title = " + title.getNodeValue());
        NodeList itemtitle = XPathAPI.selectNodeList(doc.getDocumentElement(), "//demo/item/title/text()");
        for(int i = 0; i < itemtitle.getLength(); i++) {
            System.out.println("item title = " + itemtitle.item(i).getNodeValue());
        }
        NodeList iteminfourl = XPathAPI.selectNodeList(doc.getDocumentElement(), "//demo/item/info/@url");
        for(int i = 0; i < iteminfourl.getLength(); i++) {
            System.out.println("item info url = " + iteminfourl.item(i).getNodeValue());
        }
    }
}
