Use xpath to parse xml and javaxpathxml in Java

Source: Internet
Author: User

Use xpath to parse xml and javaxpathxml in Java

Xpath is a language used to search for information in xml documents. Xpath is used to navigate through elements and attributes in XML documents. The return value may be a node, a node set, text, and a mixture of nodes and text.
Before learning this document, you should have a certain understanding of XML nodes, elements, attributes, text, processing instructions, comments, root nodes, namespaces, and node relationships, as well as 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 documentation: https://yunpan.cn/cvc4tEIGy5EvS access password 9d16
This article mainly introduces how to operate xml using xpath in Java.
1) first, how to use the xpath Technology in dom4j
Import the jar packages supported by xPath. Jaxen-1.1-beta-6.jar (first pilot into the dom4j package, dom4j: http://www.dom4j.org/dom4j-1.6.1 ).

After importing the package:

If you do not know how to import a package, refer to my previous blog: Java to get the xml node summary and read the xml document node.
2) use the xpath method in Java. There are two main points:
List <Node> selectNodes ("xpath expression"); query multiple Node objects
Node selectSingleNode ("xpath expression"); queries a Node object
The following describes how to use an instance.

I. Usage of selectNodes:

1 package com. vastsum. demo; 2 3 import java. io. file; 4 import java. io. fileOutputStream; 5 import java. util. list; 6 7 import org. dom4j. document; 8 import org. dom4j. element; 9 import org. dom4j. node; 10 import org. dom4j. io. outputFormat; 11 import org. dom4j. io. SAXReader; 12 import org. dom4j. io. XMLWriter; 13 14/** 15*16 * @ author shutu00817 * selectNode usage 18 */19 public class xpathDemo {20 21 public stat Ic void main (String [] args) throws Exception {22 23 Document doc = new SAXReader (). read (new File (". /src/contact. xml "); 24 25/** 26 * @ param xpath represents the xpath syntax variable 27 */28 String xpath =" "; 29 30/** 31*1. /absolute path indicates starting from the root position of xml or sub-elements (a hierarchy) 32 */33 xpath = "/contactList"; 34 xpath = "/contactList/contact "; 35 36/** 37*2. // relative path indicates the selection element regardless of any hierarchy. 38 */39 xpath = "// contact/name"; 40 xpath = "// name"; 41 42/** 43*3. * wildcard indicates that all elements are matched. 44 */45 xpath = "/contactList/*"; // all sub-tags under the root tag contactList 46 xpath = "/contactList //*"; // all the labels under the root tag contactList (non-hierarchical structure) 47 48/** 49*4. [] condition indicates the selected element 50 */51 // contact tag 52 with id attribute xpath = "// contact [@ id]"; 53 // The second contact tag 54 xpath = "// contact [2]"; 55 // select the last contact tag 56 xpath = "// contact [last ()] "; 57 58/** 59*5. @ attribute: select attribute node 60 */61 xpath = "// @ id"; // select the id attribute Node object, the returned Attribute object 62 xpath = "// contact [not (@ id)]"; // select the contact label node 63 xpath = "// contact [@ id = '002']" That does not contain the id attribute. // select the contact tag 64 xpath = "// contact [@ id = '001' and @ name = 'Eric ']"; // select the contact tag 65 66/** 67*6 with the id property value 001 and name attribute eric. text () indicates to select the Text content 68 */69 // select the text content under the name label, and return the text object 70 xpath = "// name/Text ()"; 71 xpath = "// contact/name [text () = 'zhang san']"; // select the name tag 72 73 74 List whose name is Zhang San <Node> list = doc. selectNodes (xpath); 75 for (Node node: list) {76 System. out. println (node); 77} 78 79 // write the xml file 80 // output location 81 FileOutputStream out = new FileOutputStream ("d:/contact. xml "); 82 83 // The specified format is 84 OutputFormat format = OutputFormat. createPrettyPrint (); 85 format. setEncoding ("UTF-8"); 86 XMLWriter writer = new XMLWriter (out, format); 87 88 // write 89 writer. write (doc); 90 91 // close resource 92 writer. close (); 93 94} 95 96 97}

Ii. Usage of selectSingleNode

1 package com. vastsum. demo; 2 3 import java. io. file; 4 import java. util. iterator; 5 6 import org. dom4j. attribute; 7 import org. dom4j. document; 8 import org. dom4j. element; 9 import org. dom4j. io. SAXReader; 10 11/** 12*13 * @ author shutu00814 * selectSingleNode use 15 */16 public class xpathDemo1 {17 public static void main (String [] args) throws Exception {18 // read the XML file and get the document Object 19 SAXReader saxReader = new SAXReader (); 20 Document doc = saxReader. read (new File (". /src/contact. xml "); 21 22 // use xpath to obtain a node 23 String xpath =" "; 24 25 // For the node with the contact element id =" 001, operation 26 xpath = "// contact [@ id = '001']"; 27 Element contactElem = (Element) doc. selectSingleNode (xpath); 28 29 // set the value of this node to 30 contactElem. addAttribute ("name", "001"); 31 32 // output all attribute values of this node 33 for (Iterator it = contactElem. attributeIterator (); it. hasNext ();) {34 Attribute conAttr = (Attribute) it. next (); 35 String conTxt = conAttr. getValue (); 36 String conAttrName = conAttr. getName (); 37 System. out. println (conAttrName + "=" + conTxt); 38} 39 40} 41}

Note: The following is an xml file for operations.

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <contactList id = "0"> 3 <contact id = "001" class = "style" name = "lisi"> 4 <name> Michael </name> 5 <age> 20 </age> 6 <phone> 134222223333 </phone> 7 <email> zhangsan@qq.com </email> 8 <qq> 432221111 </qq> 9 </contact> 10 </phone> contact id = "002"> 11 <name> Li Si </name> 12 <age> 20 </age> 13 <phone> 134222225555 </phone> 14 <email> lisi@qq.com </email> 15 <qq> 432222222 </qq> 16 </contact> 17 <contactTwo> 18 <name> Wang Wu </name> 19 <age> 32 </age> 20 <phone> 465431341 </phone> 21 <emali> af@qq.com </emali> 22 <qq> 46164694 </qq> 23 </contactTwo> 24 <test> test </test> 25 <test> other purposes </test> 26 </contactList>View Code

 

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.