import java.io.*;
import java.net.*;
import java.util.*;
import nanoxml.*;

public class QueryXML {
	public static void main (String[] args) {
		URL url;
		URLConnection urlconnection;
		PrintWriter out;
		BufferedReader in;
		StringBuffer buffer=new StringBuffer(100);
		String tempLine;
		
		XMLElement root;
		try {
			url=new URL("http://sparc68.cse.cuhk.edu.hk:8080/examples/servlet/CompareXML");
			urlconnection=url.openConnection();
			urlconnection.setDoOutput(true);
			out=new PrintWriter(urlconnection.getOutputStream());
			out.print("field=ID&query=Nelson");
			out.close();
			in=new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
			do {
				tempLine=in.readLine();
				if (tempLine!=null) {
					buffer.append(tempLine);
				} else {
					break;
				}
			} while (true);
			in.close();
			System.out.println(buffer.toString());
			
			// begin to parse the XML read from CompareXML
			
			// construct a XMLElement object
			root=new XMLElement();
			
			// call its method to read data from a string containing XML
			root.parseString(buffer.toString());
			
			// start to anaylse the XML DOM tree
			XMLElement product=findTag(root,"product");
			if (product!=null) {
				XMLElement company=findTag(product,"company");
				if (company!=null) {
					XMLElement price=findTag(company,"price");
					if (price!=null) {
						System.out.println("\nThe price is: "+price.getContents());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static XMLElement findTag(XMLElement src,String str) {
      Vector v = src.getChildren();
      for (int i = 0; i < v.size(); i++) {
         XMLElement e = (XMLElement)(v.elementAt(i));
         if (e.getTagName().compareTo(str) == 0) {
	         return e;
         } 
      }
      return null;
   }
}
