XML Learning Summary-xpath technology-(ii)

Source: Internet
Author: User

XPath technology

When using a dom4j query to compare deep hierarchies of nodes (labels, text, attributes), it is cumbersome to have the XPath technology appear

XPath function: Used to quickly get the desired node object

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

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

Delete the specified label

Package Gz.itcast.b_xpath;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 APPle * */public class Demo1 {public static void main (string[] args) throws exception{/** * Requirements: Delete Except the student tag with ID value 2 */document doc = new Saxreader (). Read (New File ("E:/student.xml"));//1. Student with ID 2 tag//use XPath technology element Stuelem = (Element) doc.selectsinglenode ("//student[@id = ' 2 ')",//2. Delete label Stuelem.detach ();//3. Write out the 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 ();}}

Package Gz.itcast.b_xpath;import Java.io.file;import Java.util.list;import org.dom4j.document;import Org.dom4j.Node  Import org.dom4j.io.saxreader;/** * Learn XPath expression syntax * @author APPle * */public class Demo2 {public static void main (string[] args) throws Exception {Document doc = new Saxreader (). Read (New File ("./src/contact.xml"));  String XPath = "";/** * 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 label node that does not contain the id attribute XPath = "//contact[@id = ' 002 ']";//select the contact label with the value 002 for the id attribute xpath = "//contact[@id = ' 001 ' and @name = ' Eric ']";//select the id attribute value 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 Zhang San name tag list<node> list = Doc.selectnodes (XPath); for (node node:list) {System.out.println (node);}}}

  

Read XML file impersonate user login

Package Gz.itcast.b_xpath;import Java.io.bufferedreader;import Java.io.file;import java.io.InputStreamReader; Import Org.dom4j.document;import org.dom4j.element;import org.dom4j.io.saxreader;/** * XPath case: Impersonate user Login Effect * @author APPle * */public class Demo3 {public static void main (string[] args) throws exception{//1. Gets the user name and password entered by the user bufferedreader br = New BufferedReader (New InputStreamReader (system.in)); System.out.println ("Please enter user name:"); String name = Br.readline (); System.out.println ("Please enter password:"); String password = br.readline ();//2. To the database, query whether there is a corresponding user//corresponding User:  found in the User.xml file a   //name attribute value of ' User input ', and the password attribute value is ' user input ' of the username doc = new Saxreader (). Read (New File ("./src/user.xml")); Element Userelem = (Element) Doc.selectsinglenode ("//user[@name = '" +name + "and @password = '" +password+ "']"); if ( Userelem!=null) {//Login succeeded System.out.println ("login Successful");} else{//Login failed System.out.println ("Login Failed");}}}

Reading HTML Document contents

Package Gz.itcast.b_xpath;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 APPle * */public class Demo4 {public static void main (string[] args) throws exception{document doc = new Saxreader (). Read ( New File ("./src/personlist.html"));//system.out.println (doc);//Read 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);}}}

 

XML Learning Summary-xpath technology-(ii)

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.