Support Wikipedia Follow My Heart: How to use XPATH in XML


How to use XPATH in XML

First ,  you need to use some tool (i.e. Dom4j) to read in an XML file (as your source file).

String filename = "C:\\Test\\myTest.xml"; 
SAXReader reader = new SAXReader(); 
Document doc = null; 
try {    doc = File(filename));} 
catch (MalformedURLException e) {    e.printStackTrace();} catch (DocumentException e) {    e.printStackTrace();}

Second, You need to define the XPath expression. (Not necessary but recommended to write them in separate code)
String findAllBread = "//bread";     
/* any element whose tag is "bread"  */

String findMyMilk = "//person[@name='me']/milk";     
/** any element whose name is "milk" and, is the direct child of element (tag "person"), and the parent element has attribute "name", and the value of "name" attribute is "me" */
Please refer to for detail of XPATH grammar

Third, you can use your xpath expression to get corresponding content now.

List breads = doc.selectNodes(findAllBread);
Element myMilk = (Element) doc.selectSingleNode(findMyMilk);
for (Iterator iter = breads.iterator();iter.hasNext();){
Element ele = (Element);
System.out.println("Bread  Weight="+ele.attributeValue("weight"));
System.out.println("My Milk is "+myMilk.attributeValue("weight"));


XML file (breakfirst.xml)

<?xml version="1.0" encoding="UTF-8"?>
<person name="me">
<message>You have new Email Today</message>
<bread weight="100g"></bread>
<milk weight="200g"></milk>
<egg number="1"></egg>
<person name="bill">
<message>You Have to go to school today</message>
<bread weight="200g"></bread>
<milk weight="500g"></milk>
<egg number="1"></egg>


Bread  Weight=100g
Bread  Weight=200g
My Milk is 200g