Create an XML document and search by XPath : XPath « XML « Java






Create an XML document and search by XPath

    

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class MainClass {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document retval = dbf.newDocumentBuilder().newDocument();
    Element parent = retval.createElement("parent");
    retval.appendChild(parent);

    Element child1 = retval.createElement("child");
    child1.setTextContent("child.text");
    parent.appendChild(child1);
    Element child2 = retval.createElement("child");
    child2.setTextContent("child.text.2");
    parent.appendChild(child2);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    System.out.println(xPath.evaluate("//child/text()", retval, XPathConstants.NODE).getClass());

  }

}

   
    
    
  








Related examples in the same category

1.Use XPath to select node
2.Shallow print of node list
3.Deep print of node list
4.Parse with XPath
5.XML and XPath utilities
6.Get the String data associated with the XPath selection supplied
7.This program evaluates XPath expressions