// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.xml.xpath;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

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

import net.sf.practicalxml.xpath.SimpleNamespaceResolver;


/**
 *  An example XPath against a namespaced document, using <code>SimpleNamespaceResolver</code>
 *  from the Practical XML library.
 */
public class SimpleNamespacedXPathExample
{
    public static void main(String[] argv) throws Exception
    {
        String xml = "<foo xmlns='http://www.example.com/example'>"
                   + "    <bar name='argle'>"
                   +          "Argle"
                   + "    </bar>"
                   + "    <bar name='bargle'>"
                   +          "Bargle"
                   + "        <baz>Baz</baz>"
                   + "    </bar>"
                   + "</foo>";

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new InputSource(new StringReader(xml)));

        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new SimpleNamespaceResolver("ns", "http://www.example.com/example"));

        String result = xpath.evaluate("/ns:foo/ns:bar/ns:baz", dom);
        System.out.println("selected content: \"" + result + "\"");
    }
}
