package przyklady.software;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathConstants;
import org.xml.sax.InputSource;

import util.Args;

import org.w3c.dom.NodeList;

/** Przyklad do artykulu "XML w Javie 5.0" (Software 2.0, 6/2005).
    Przyklad obliczania wyrazen XPath.
    Marzec 2005
    @author Patryk Czarnik
*/
public class XPathExample {
   public static void main(String args[]) {
	  args = Args.argsOrDefault(args, "sklep.xml", "//towar[@id-kategorii = 'herbata']", "nazwa");
      String docURI = args[0];
      String expr1 = args[1];
      String expr2 = args[2];

      try {
         XPath xpath = XPathFactory.newInstance().newXPath();
         InputSource inputSource = new InputSource(docURI);
         System.out.println("Obliczanie pierwszego wyrazenia.");
         NodeList nodes = (NodeList) xpath.evaluate(expr1, inputSource, XPathConstants.NODESET);

         System.out.println("Pierwszy wynik zawiera " + nodes.getLength() + " wezlow.");
         if(nodes.getLength() > 0) {
            System.out.println("Obliczanie drugiego wyrazenia.");
            String result = xpath.evaluate(expr2, nodes.item(0));
            System.out.println("Wynik drugiego wyrazenia to:");
            System.out.println(result);
         }
      } catch(Exception e) {
         System.out.println(e.getMessage());
         e.printStackTrace();
      }
   }
}
