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

2011年10月4日星期二

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 = reader.read(new 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 http://www.w3schools.com/xpath/ 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)iter.next();
System.out.println("Bread  Weight="+ele.attributeValue("weight"));
}
System.out.println("My Milk is "+myMilk.attributeValue("weight"));




Result:

XML file (breakfirst.xml)
------------------------------------------------------------------

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



Result:
------------------------------------------------------------------

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


-------------------------------------------------------------------------

没有评论:

发表评论