import javax.xml.transform.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
/**
 * Curious JAXP/XSLT/XPATH interaction behaviour that I hope is a bug.
 * @author Jon Mountjoy
 */
class Jon {

/**
 */
public static void main(String[] args) {
	Jon j = new Jon();
	try {
		j.run();
	} catch (Exception e) {
		e.printStackTrace();
	}

}


/**
 */
public void run() throws Exception {

	String XML =
		"<outer><para> Here is a glossary item <glossterm linkend='xml'>system</glossterm> </para>" +
		 " <glossary>   	  <glossentry id='xml'>	   	    <glossdef>	   	       <para>FOOBAR</para>	   	    </glossdef>	   	  </glossentry>	   </glossary>"  +
		 " </outer>";

 	String XSL =
 		"<xsl:stylesheet  xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>" + 
 		"<xsl:template match='glossterm'>" +
 		  "Number of glossary items  <xsl:value-of select='count(//glossary/glossentry)'/>" +
 		"</xsl:template></xsl:stylesheet>";

  	// First we parse the XML 		
	DOMParser parser = new DOMParser();
	parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(XML)));

	Document dd = parser.getDocument();
	Node pp = dd.getFirstChild();

	System.err.println("Document has " + dd.getChildNodes().getLength() + " child and its element name is " + dd.getChildNodes().item(0).getNodeName());
	
	// Now I create two DOM Sources.  One is on the document as a whole, the other is on its
	// first (and only) child.
	
	javax.xml.transform.dom.DOMSource domsrc1 = new javax.xml.transform.dom.DOMSource(dd);
	javax.xml.transform.dom.DOMSource domsrc2 = new javax.xml.transform.dom.DOMSource(pp);


	// Create a Transfomer
	TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance();
	Templates template = null;
	template = tFactory.newTemplates(new javax.xml.transform.stream.StreamSource(new java.io.StringReader(XSL)));

	// Now for the action - apply the same transfomer to the two different DOM Sources
	System.out.println("This works");
	template.newTransformer().transform(domsrc1, new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out)));

	System.out.println("\n\nThis does NOT work (no matches for //glossary//glossentry)");
	template.newTransformer().transform(domsrc2, new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out)));

	//Interestingly, if I do the same for the style sheet //glossary I get 1 on both counts, and if I do
	// it for //glossentry I also get 1 on both counts.

	// Its as if glossary and glossentry aren't related when I do the transform with the node instead of document!!
}
}