Package com.skaringa.javaxml.example

Source Code of com.skaringa.javaxml.example.XPathExample

package com.skaringa.javaxml.example;

import java.util.ArrayList;
import java.util.Collection;

import com.skaringa.javaxml.ObjectTransformer;
import com.skaringa.javaxml.ObjectTransformerFactory;

/**
* Demonstrate how to perform XPath-Queries against Java objects.
*/
public final class XPathExample {

  /**
   * MAIN.
   * @param args Program arguments (not used).
   */
  public static void main(String[] args) {

    // a collection of people
    Collection people = new ArrayList();
    people.add(new Person(101, "Bilbo", "Beutlin", "bb@email.com"));
    people.add(new Person(102, "Fred", "Feuerstein", "ff@email.com"));

    try {
      // the collection has to be converted into a DOM tree
      // to perform XPath-Queries.
      javax.xml.parsers.DocumentBuilder docBuilder =
        javax
          .xml
          .parsers
          .DocumentBuilderFactory
          .newInstance()
          .newDocumentBuilder();
      org.w3c.dom.Document doc = docBuilder.newDocument();

      ObjectTransformer trans =
        ObjectTransformerFactory.getInstance().getImplementation();
      trans.serialize(people, new javax.xml.transform.dom.DOMResult(doc));

      // Use XPath to find the collection element
      // of the person whose last name is ...
      String xPathQuery = "//cel[lastName='Feuerstein']";
      org.w3c.dom.Node ffNode = null;

      // if Java 1.5 >>
//      javax.xml.xpath.XPath xpath =
//        javax.xml.xpath.XPathFactory.newInstance().newXPath();
//      ffNode =
//        (org.w3c.dom.Node) xpath.evaluate(
//          xPathQuery,
//          doc,
//          javax.xml.xpath.XPathConstants.NODE);
      // << endif Java 1.5

      // if Java 1.4 >>
//      ffNode = org.apache.xpath.XPathAPI.selectSingleNode(doc, xPathQuery);
      // << endif Java 1.4

      // deserialize the node into a person
      if (ffNode != null) {
        Person p =
          (Person) trans.deserialize(
            new javax.xml.transform.dom.DOMSource(ffNode));
        System.out.println(p);
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Hide ctor because this is an utility class.
   */
  private XPathExample() {
  }
}
TOP

Related Classes of com.skaringa.javaxml.example.XPathExample

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.