import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlObject;

/**
 * Date: Apr 17, 2007
 *
 * @author jacobd
 */
public class XPathRepro {
    private static String namespace = "http://www.bsource.ch/bs";
    private static String namespaceDeclaration = "declare namespace bs='" + namespace + "';";
    private static String docContent = "<bs:bookstore xmlns:bs=\"http://www.bsource.ch/bs\">\n" +
            "   <book>\n" +
            "       <id>1</id>\n" +
            "       <author>author1</author>\n" +
            "       <title>title1</title>\n" +
            "   </book>\n" +
            "   <book>\n" +
            "       <id>2</id>\n" +
            "       <author>author2</author>\n" +
            "       <title>title2</title>\n" +
            "   </book>\n" +
            "</bs:bookstore>";

    public static void main(String[] args) throws Exception {

        XmlObject[] elems = null;

        try {
            XmlObject document = XmlObject.Factory.parse(docContent);

            XmlOptions opts = new XmlOptions();
            opts.setSavePrettyPrint();
            opts.setSavePrettyPrintIndent(4);
            System.out.println(document.xmlText(opts));
            elems = document.selectPath(namespaceDeclaration + "$this/bs:bookstore/book[author='author2']/author");
            System.out.println("START - PRINTING ELEMENTS");
            for (int i = 0; i < elems.length; i++) {
                System.out.println("ELEMENT["+i+"]-"+elems[i].xmlText(opts));
            }
            System.out.println("END - PRINTING ELEMENTS");

        }
        catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        if (elems.length == 0)
            throw new Exception("no result found for the given path expression");
    }
}
