<computers>
<windows>
<lenovo model="g50">
<year>2015</year>
</lenovo>
<lenovo model="g5040">
<year>2014</year>
</lenovo>
<asus>
<year>2015</year>
</asus>
<dell>
<year>2014</year>
</dell>
</windows>
<osx>
<macbookpro>
<year>2014</year>
</macbookpro>
</osx>
</computers>
package com.broodcamp.xstream_demo;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author Edward P. Legaspi
**/
public class XPathDemo {
public static void main(String[] args) {
try {
new XPathDemo();
} catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException
| TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public XPathDemo() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
TransformerException {
ClassLoader classLoader = getClass().getClassLoader();
File fXmlFile = new File(classLoader.getResource("xpath_demo.xml").getFile());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
Transformer trans = TransformerFactory.newInstance().newTransformer();
StringWriter writer = new StringWriter();
trans.transform(new DOMSource(doc), new StreamResult(writer));
System.out.println(writer.getBuffer().toString().replaceAll("\n|\r", ""));
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/computers/windows/lenovo[year/text()='2014']");
Object result = expr.evaluate(doc, XPathConstants.NODE);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("nodes: " + nodes.item(i).getTextContent());
}
}
}