Parsing XML using XPath in Java

Source: Internet
Author: User
Tags xpath

XPath is a language that looks for information in an XML document. XPath is used to navigate through elements and attributes in an XML document. Its return value may be a node, a node collection, text, and a mixture of nodes and text.
Before you learn this document, you should have a certain understanding of XML nodes, elements, attributes, text, processing instructions, annotations, root nodes, namespaces, and node relationships, as well as an understanding of XPath.
XML Learning Address:http://www.runoob.com/xml/xml-tutorial.html
XPath basic Syntax learning address:http://www.runoob.com/xpath/xpath-tutorial.html
XPath Official document:Https://yunpan.cn/cvc4tEIGy5EvS access password 9d16
This article focuses on: Using XPath operations on XML operations in Java.
1) How to use XPath technology first in dom4j
Imports the supported jar packages for XPath. Jaxen-1.1-beta-6.jar (first import dom4j package, dom4j:http://www.dom4j.org/dom4j-1.6.1/).

After the Guide package:

If you do not know how to guide the package please refer to my previous blog:java Get XML node summary read XML document node
2) using the XPath method in Java, there are two main points:
List<node> selectnodes ("XPath expression"); Querying multiple Node objects
Node selectSingleNode ("XPath expression"); Querying a Node object
Here's an example of how to use it.

First, selectnodes use method:

1  PackageCom.vastsum.demo;2 3 ImportJava.io.File;4 ImportJava.io.FileOutputStream;5 Importjava.util.List;6 7 Importorg.dom4j.Document;8 Importorg.dom4j.Element;9 ImportOrg.dom4j.Node;Ten ImportOrg.dom4j.io.OutputFormat; One ImportOrg.dom4j.io.SAXReader; A ImportOrg.dom4j.io.XMLWriter; -  - /** the  *  -  * @authorshutu008 - How to use *selectnode -  */ +  Public classXpathdemo { -  +      Public Static voidMain (string[] args)throwsException { A  atDocument doc =NewSaxreader (). Read (NewFile ("./src/contact.xml"))); -          -         /** -          * @paramXPath represents the XPath syntax variable -          */ -String xpath= ""; in          -         /** to * 1. /absolute path represents the beginning of the root position of the XML or child element (a hierarchy) +          */ -XPath = "/contactlist"; theXPath = "/contactlist/contact"; *          $         /**Panax Notoginseng * 2.//The relative path represents a selection element that is not divided into any hierarchy.  -          */ theXPath = "//contact/name"; +XPath = "//name"; A          the         /** + * 3. * Wildcard character means matching all elements -          */ $XPath = "/contactlist/*";//all sub-labels under the root tag contactlist $XPath = "/contactlist//*";//all tags under the root tag contactlist (no hierarchy) -          -         /** the * 4. [] condition indicates which element is selected under what conditions -          */Wuyi         //Contact label with id attribute theXPath = "//contact[@id]"; -         //the second contact label WuXPath = "//contact[2]"; -         //Select the last contact label AboutXPath = "//contact[last ()]"; $          -         /** - * 5. The @ attribute indicates the Select attribute node -          */ AXPath = "//@id";//Select the id attribute node object, which returns the attribute object +XPath = "//contact[not (@id)]";//Select the contact label node that does not contain an id attribute theXPath = "//contact[@id = ' 002 ']";//Select the contact label with an id attribute value of 002 -XPath = "//contact[@id = ' 001 ' and @name = ' Eric ']";//Select the id attribute value of 001, and the Name property is Eric's contact label $          the         /** the *6. Text () indicates selection of textual content the          */ the         //Select the text content under the name label to return to the TextBox object -XPath = "//name/text ()"; inXPath = "//contact/name[text () = ' Zhang San ']";//Select the name tag named Zhang San the          the          Aboutlist<node> list =Doc.selectnodes (XPath); the          for(Node node:list) { the System.out.println (node); the         } +      -         //write out an XML file the         //Output PositionBayiFileOutputStream out =NewFileOutputStream ("D:/contact.xml"); the          the         //Specify Format -OutputFormat format =outputformat.createprettyprint (); -Format.setencoding ("Utf-8"); theXMLWriter writer =NewXMLWriter (Out,format); the          the         //Write Content the Writer.write (DOC); -          the         //Close Resource the writer.close (); the         94     } the      the  the}

Second, the use of selectSingleNode method

1  PackageCom.vastsum.demo;2 3 ImportJava.io.File;4 ImportJava.util.Iterator;5 6 ImportOrg.dom4j.Attribute;7 Importorg.dom4j.Document;8 Importorg.dom4j.Element;9 ImportOrg.dom4j.io.SAXReader;Ten  One /** A  *  -  * @authorshutu008 - Use of *selectsinglenode the  */ -   Public classxpathdemo1{ -       Public Static voidMain (string[] args)throwsexception{ -          //read the XML file to get the Document object +Saxreader Saxreader =NewSaxreader ();  -Document doc = Saxreader.read (NewFile ("./src/contact.xml"))); +          A         //get a node using XPath atString XPath = ""; -          -         //for the Contact element id= "001" node, the Operation -XPath = "//contact[@id = ' 001 ']"; -Element Contactelem =(Element) Doc.selectsinglenode (XPath); -          in         //set the attribute value for this node -Contactelem.addattribute ("name", "001"); to          +         //outputs all attribute values for this node -          for(Iterator it =contactelem.attributeiterator (); It.hasnext ();) { theAttribute conattr =(Attribute) It.next (); *String Contxt =Conattr.getvalue (); $String Conattrname =conattr.getname ();Panax NotoginsengSystem.out.println (conattrname+ "=" +contxt); -         } the          +      } A}

Note: The following is an XML file of the operation

1<?xml version= "1.0" encoding= "UTF-8"?>2<contactlist id= "0" >3<contact id= "001"class= "Style" Name= "Lisi" >4<name> Zhang San </name>5<age>20</age>6<phone>134222223333</phone>7<email>[email protected]</email>8<qq>432221111</qq>9</contact>Ten<contact id= "002" > One<name> John Doe </name> A<age>20</age> -<phone>134222225555</phone> -<email>[email protected]</email> the<qq>432222222</qq> -</contact> -<contactTwo> -<name> Harry </name> +<age>32</age> -<phone>465431341</phone> +<emali>[email protected]</emali> A<qq>46164694</qq> at</contactTwo> -<test> Testing </test> -<test> Other uses </test> -</contactList>
View Code

Parsing XML using XPath in Java

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.