package test;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;

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);
            XmlObject document = XPathRepro.createDocument();

            XmlOptions opts = new XmlOptions();
            opts.setSavePrettyPrint();
            opts.setSavePrettyPrintIndent(4);
            System.out.println("### main:\n" + 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");
    }
    
    public static XmlObject createDocument()
    {
    	XmlObject document = XmlObject.Factory.newInstance();
    	XmlCursor cursor   = document.newCursor();
    	cursor.toNextToken();
    	cursor.beginElement("bookstore", namespace);
		cursor.beginElement("book");
		cursor.insertElementWithText("id",     "1");
		cursor.insertElementWithText("author", "author1");
		cursor.insertElementWithText("title",  "title1");
		cursor.toNextToken();
		cursor.beginElement("book");
		cursor.insertElementWithText("id",     "2");
		cursor.insertElementWithText("author", "author2");
		cursor.insertElementWithText("title",  "title2");
		cursor.toNextToken();
		
        XmlOptions opts = new XmlOptions();
        opts.setSavePrettyPrint();
        opts.setSavePrettyPrintIndent(4);
        System.out.println("### createDocument:\n" + document.xmlText(opts));
    	return document;
    }
}
