Java EE XML XPath

Source: Internet
Author: User
Tags gettext xml xpath xpath

Java EE XML XPath

@author Ixenos

XPath Technology 1 introduced

Problem: When using dom4j query to compare deep hierarchies of nodes (tags, attributes, text), compare the trouble!!! You need to traverse the many nodes of the DOM tree to find it!

such as Rootele.element ("Dsfs"). Element ("SDFSF") Element ("SDFSF"). Element ("aim")

2 XPath effect

It is primarily used to quickly get the desired node object.

(The value of the Match property in XSLT uses the xpath!!! )

3 How to use XPath technology in DOM4J

1) Import the XPath support jar package. Jaxen-1.1-beta-6.jar

2) using the XPath method

List<node> selectnodes ("XPath expression"); Querying multiple Node objects

Node selectSingleNode ("XPath expression"); Querying a Node object

4 XPath syntax

/absolute path represents the beginning of the root position of the XML or child element (a hierarchy)

A relative path represents a selection element that is not divided into any hierarchy.

* Wildcard means matching all elements

[] condition indicates which element is selected under what conditions

The @ property represents the Select Attribute node

and relationships (equivalent to &&) of conditions

Text () literal indicates selection of text content

Example:

XPath can describe a node set in an XML document

/grib/row

Describes all the row elements in the Grib (each grib) child element

/GRIB/ROW[1]

Select a specific element with [], which indicates the first row (the index starts at 1)

/grib/row[1]/cell[1]/@anchor

Get the attribute value with @, which describes the anchor property of the first cell in the first row

/grib/row/cell/@anchor

The Anchor property of all cells in the row element that describes the child elements of the grib as the root element

/** * 1. The/absolute path represents the beginning of the root position of the XML or child element (a hierarchy) */xpath = "/contactlist"; xpath = "/contactlist/contact";/** * 2. A relative path represents a selection element that is not divided into any hierarchy. */xpath = "//contact/name"; xpath = "//name";/** * 3. * Wildcard means match all elements */xpath = "/contactlist/*"; All child tags under the root tag contactlist xpath = "/contactlist//*";//All labels under the root tag contactlist (no hierarchy)/** * 4. [] Conditions indicate what conditions are selected for the element *///with the id attribute of the contact label XPath = "//contact[@id]";//the second contact tag XPath = "//contact[2]";//Select the most After a contact tag XPath = "//contact[last ()]";/** * 5. The @ attribute indicates the Select attribute node */xpath = "//@id"; Select the id attribute node object that returns the attribute object XPath = "//contact[not (@id)]";//select the contact tag node XPath = "//contact[@id = ' 002 ']" that does not contain the id attribute;//  Select the contact label with the ID property value of 002 XPath = "//contact[@id = ' 001 ' and @name = ' Eric ']";//Select the ID property value is 001, and the Name property is Eric's contact label/** *6. Text () to select text content *///Select the text content under the name label, return text Object XPath = "//name/text ()"; XPath = "//contact/name[text () = ' Zhang San ']";// Select the name tag named Zhang San 

  For more XPath expressions, see XPath Tutorial

Demo:
Import Java.io.file;import java.io.fileoutputstream;import Org.dom4j.document;import Org.dom4j.Element;import Org.dom4j.io.outputformat;import Org.dom4j.io.saxreader;import org.dom4j.io.xmlwriter;/** * First XPath program * @author Ixenos * */public class Demo1 {public static void main (string[] args) throws exception{/** * Requirements: Delete student tag with ID value 2 */document d OC = new Saxreader (). Read (New File ("E:/student.xml"))//1. Query ID 2 student tag//Use XPath technology Element Stuelem = (Element) Doc.selectsinglenode ("//student[@id = ' 2 ']");//2. Delete label Stuelem.detach ();//3. write XML file FileOutputStream out = new FileOutputStream ("E:/student.xml"); OutputFormat format = Outputformat.createprettyprint (); Format.setencoding (" Utf-8 "); XMLWriter writer = new XMLWriter (Out,format); Writer.write (doc); Writer.close ();}}

  

Brief example

 1) Use the XPath to locate the label, and modify the operation

Package Com.ixenos.xpath;import Java.util.list;import Org.dom4j.document;import org.dom4j.element;import Org.dom4j.io.saxreader;import com.ixenos.dom4j.createxml;/** * Improved on the basis of Testxpath: * The precise positioning is given to the XPath to do, So delete the Modele extra attribute location judgment * * @author Ixenos * */public class TestXPath2 {/** * Read XML file Generation docment * * @throws Exception */PUBL IC Static Document Getdoc (String path) throws Exception {Document doc = new Saxreader (). read (path); return doc;} /** * XPath positioning label */@SuppressWarnings ("unchecked") public static list<element> Getele (Document doc, String XPath) { Return (list<element>) doc.selectnodes (XPath);}            /** * Modify the properties of the specified tag * * @param func * Modify function Selection * @param elelist * Modified label list * @param locateattr * Property used to position the label * @param locateattrvalue * Property value for the property that is used to position the label * @param aimchild * sub-label to be modified * @param aim Childtext * The new child label literal value that you want to modify */public static void Modele (string func, list<element> elelist, String aimchild , String Aimchildtext) {// Remove the for (Element ele:elelist) {//Modify function Select if ("Delete". Equals (func)) {Ele.detach ();} else if ("Modify". Equals (func)) {//Modify Specifies the property value of the property//element (name) specifies that the first label named name is a label//setText Modify Text,addtext Append textele.element (aimchild). SetText (Aimchildtext );}}} /** * Output The DOM tree as an XML file * * @throws Exception */public static void WriteXML (Document doc, Boolean pretty, String encoding) th Rows Exception {createxml.writexml (doc, pretty, encoding);} /** * Test * * @param args * @throws Exception */public static void Main (string[] args) throws Exception {Document doc = ge Tdoc ("Demo.xml");//Get all id attribute value 2 Student label list<element> elelist = Getele (Doc, "//student[@id = ' 2 ']"); Modele (" Modify ", Elelist," name "," Lee Ya ");//Modele (" delete ", elelist, NULL, NULL); WriteXML (Doc, True," Utf-8 ");}}

  

To modify the result:

<?xml version= "1.0" encoding= "Utf-8"?><students> <student   id= "1" >     <name> Zhang San </ name>      <gender> men </gender>      <grade> Internet of Things </grade>      <address> Guangzhou Baiyun </ address>   </Student>    <student id= "2" >     <name> ya </name>      <gender> women </gender>      <grade> IoT class </grade>      <address> Guangzhou Haizhu </address>   </ Student> </Students>

  

2) Use XPath to read a canonical HTML file (such as XHTML)

Import Java.io.file;import java.util.iterator;import Java.util.list;import Org.dom4j.document;import Org.dom4j.element;import org.dom4j.io.saxreader;/** * Use XPath technology to read a canonical HTML document * @author Ixenos * */public class Demo4 {Pub Lic static void Main (string[] args) throws exception{document doc = new Saxreader (). Read (New File ("./src/personlist.html") );//system.out.println (doc);//Read the title tag Element Titleelem = (Element) Doc.selectsinglenode ("//title"); String title = Titleelem.gettext ();  System.out.println (title);/** * Exercise: Read all information about a contact * output in the following format: * No.: 001 name: Zhang San Sex: Male Age: 18 Address: xxxx Tel: xxxx * No: 002 Name: John Doe Gender: Female Age: 20 Address: xxxx Tel: xxxx * ... *///1. Read all tbody in the TR label list<element> list = (list<element>) doc.sele Ctnodes ("//tbody/tr");//2. Traverse for (element Elem:list) {//number//string id = (element) elem.elements (). Get (0)). GetText (); String id = Elem.selectsinglenode ("td[1]"). GetText ();//Name String name = (Element) elem.elements (). Get (1)). GetText (); /gender string gender = (Element) elem.elements (). Get (2)). GetText ();//Age string ages = (Element) elem.elements (). Get (3)). GetText ();//Address String = ((Element) Elem.elements (). Get (4)). GetText ();//Telephone string phone = (Element) elem.elements (). Get (5)). GetText (); System.out.println ("Number:" +id+ "\ t name:" +name+ "\ T Gender:" +gender+ "\ T Age:" +age+ "\ T address:" +address+ "\ t Tel:" +phone);}}}

  

Java EE XML XPath

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.