Mega Code Archive

 
Categories / Java / XML
 

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());   } }