Java --- parsing of XML (2) - Dom4j parsing / XPath

Familiar with memory 2021-01-21 12:56:43
java parsing xml dom4j dom


Dom4j: Dom SUN dom At loading time , Load all elements into memory DOM4j - The third party .

Dom4j It's open source 、 agile XML API. At present, many open source frameworks such as struts,hibernate All use dom4j As an analysis of its xml Tools for . Support document reading and writing function and Xpath Quick query operation .

This requires us to import its package into myeclipse Medium . Get ready DOM4j: package :dom4j.x.jar Package structure : org.dom4j class org.dom4j.io.SAXReader – xml Document parser org.dom4j.Document、Element – Document object Need to know Element Some of the ways Element.element(“name”) – The first one under this element name Elements . Element.elementIterator(“name”) – All... Under this element name Elements . return Iterator Element.getText() – Returns the text contained in the element . Element.getAttribute(“name”) – The return name is name Properties of . Element.addElement(“name”); - Add one name Elements , At the same time return to name The element itself . org.dom4j.io.XMLWriter – take Document The object of writing .

DOM4J The hierarchy of :

Use UTF-8 code , Solve the Chinese garbled code :

// Declaration encoding format
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
// preservation (XMLWriter By default, it uses UTF-8 code . therefore , If you use OutputStream preservation , And it happens to be UTF-8 code , You don't have to worry about garbled code )
XMLWriter xml = new XMLWriter(new FileOutputStream("./src/xml/a.xml"),format);
xml.write(doc);

Dom4j- Save node - Deal with Chinese code :

 stay JavaIO in ,writer Always process data in local encoding format . namely GB2312
all , Use writer There may be some problems with writing out the data , If not completely preserved , Or random code :
XMLWriter writer = new XMLWriter(new FileWriter(“a.xml”));
// Writing data
writer.write(doc);
therefore , It is suggested that when writing data , Use OutputStream Save the data .

remember : When deleting a node , To delete it with its parent node .

Methods to add or modify properties :addAttribute

Dom4j- From no to no generation of a new xml:

// adopt DocumentHelper Create a... In memory Document
Document doc = DocumentHelper.createDocument();
doc.setXMLEncoding(“UTF-8”);//XML The encoding format of
// Generate a node , The first node generated is also the root node , This method is used only once
Element root = doc.addElement(“users”);

Xpath

XML PATH Language.
Can achieve fast query .
XPATH contain
XPath Using path expressions in XML Navigation in the document .
XPath Contains a library of standard functions
Get ready Xpath My bag :
jaxen.jar
Xpath Use... In the following ways
dom.selectNodes – Return to one List Antithetic image
dom.selectSingleNode – Return to one Node Antithetic image
// Select all below user node , Here's the rule for dealing with security without a namespace
List<Element> list = doc.selectNodes("//user");
System.err.println(list.size());
// Choose all of the following name node
list = doc.selectNodes("//name");// Or start with :/users//name
System.err.println(list.size());
// The following choices are with country Attribute's node
list = doc.selectNodes("//user[@country]");
System.err.println(list.size());
// Choosing a country is EN The node of , You can use the following methods to query user login
// If country If it can't be repeated, it can be used selectSingleNode
// You can use either double quotation marks or single quotation marks ://user
Node node = doc.selectSingleNode("//user[@country=\"EN\"]");
System.err.println(node);
Xpath By querying the value of the child element , The difference between the main elements :
Such as :XML The documents are as follows :
<books>
<book id=“A001”>
<name>Oracle Programming based </name>
<price>89.99</price>
</book>
</books>
The query contains Oracle All of the word book Elements .
//book[name=‘Oracle’] // Query child elements exactly name The value of is Oracle Of book Elements
// Here's a fuzzy query
//book[contains(name,’Oracle’)]
// Can also be name The value of the element is lowercase
//book[contains(fn:lower-case(name),’oracle’]

A little bit about this : Xpath Dealing with XML file :

SAXReader sax = new SAXReader();
// Make a statement map Used to save the namespace
Map<String,String> uris = new HashMap<String, String>();
// Give the namespace an alias
uris.put("a", "http://www.itcast.cn");
// Set the namespace before reading xml file
sax.getDocumentFactory().setXPathNamespaceURIs(uris);
Document dom = sax.read("./xml2/a.xml");
// Then use the prefix with the namespace to query .
dom.selectNodes(“//a:book”);
// The query with attributes is the same as before
dom.selectNodes(//a:book[@id]
// Queries with elements must be prefixed with a namespace
dom.seletNodes(“//a:book[a:name=‘oralce’]”); // The value of the query sub element is oracle Of book Elements 

SAX,StAX Fast reading speed . All are JAXP Members of . StAX-Iterator Programming interface and Cursor Programming interface (API) . Dom4j.Dom. All nodes are loaded into memory .CRUD Very convenient . Dom4j Support XPath.

Demo code :::

package cn.hncu.dom4j;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class Dom4jDemo {
@Test
public void readDemo() throws Exception{
// Statement SAXReader Core read (xml) class , And get dom object
SAXReader sax = new SAXReader();
Document dom = sax.read("xml5/users.xml");
// Get root node
Element root = dom.getRootElement();
// Get the first child element inside
Element user = root.element("user");
String id = user.attributeValue("id");
System.out.println(id);
String name = user.element("name").getText();// Get the text content in the child element -- Law 1
String age = user.elementText("age");// Get the text content in the child element -- Law 2
System.out.println(name+","+age);
}
// Show ( Traverse ) All users
@Test
public void readAll() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("xml5/users.xml");
Element root = document.getRootElement();
Iterator<Element> it = root.elementIterator();
while(it.hasNext()){
Element e = it.next();
String id = e.attributeValue("id");
String name = e.elementText("name");
String age = e.element("age").getText();
System.out.println("id:"+id+",name:"+name+",age:"+age);
}
}
// Add one user Elements
@Test
public void addElement() throws Exception{
SAXReader sax= new SAXReader();
Document document = sax.read("xml5/users.xml");
Element root = document.getRootElement();
Element e = root.addElement("user");
e.addAttribute("id", "C003");
Element eName = e.addElement("name");
eName.setText(" Zhang San ");
Element eAge = e.addElement("age");
eAge.setText("24");
// To put the memory in dom Object is written to disk
// Law 1 --- Limited function
// FileWriter fw = new FileWriter("xml5/users.xml");// Output to console
// document.write(fw);
// fw.close();
// Law two --- More powerful
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileWriter("xml5/users.xml"), format);
// In the specified output format , hold dom Output to the specified destination ( file )
writer.write(document);
writer.close();
}
// Delete the last one user Elements
@Test
public void delElement() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read("xml5/users.xml");
Element root = document.getRootElement();
List<Element> list = root.elements();
Element e = list.get(list.size()-1);
e.getParent().remove(e);
// preservation
XMLWriter writer = new XMLWriter(new FileWriter("xml5/users.xml"));
writer.write(document);
writer.close();
}
// Create one from scratch xml file
@Test
public void createNewXml() throws IOException, FileNotFoundException{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("hncu");
root.addElement("department").addAttribute("id", "hncu001").addElement("xky").setText(" School of information science and engineering ");
// preservation
XMLWriter writer = new XMLWriter(new FileOutputStream("xml5/hncu.xml"));
writer.write(document);
writer.close();
}
//xpath Usage of
@Test
public void xpathDemo() throws Exception{
SAXReader sax = new SAXReader();
Document dom = sax.read("xml5/contact.xml");
//String xpath = "/*/name";// first / Represents the current element
//String xpath="//contact/name";// choice contact Below name( son )
//String xpath="//aaa/preceding::*";// choice <aaa> All the elements in the front
String xpath="//*[@id]";// Choose to have id All elements of the property
Element root = dom.getRootElement();
System.out.println(root.getName());
List<Element> list = root.selectNodes(xpath);
for(Element e:list){
System.out.println(e.getName()+"--"+e.getText());
}
}
//xpath usage
@Test
public void xpathDemo2() throws Exception {
SAXReader sax = new SAXReader();
Document dom = sax.read("xml5/contact.xml");
Scanner sc = new Scanner(System.in);
String name =sc.next();
//name=name.toLowerCase();
String pwd = sc.next();
//String xpath="//user[@name][@pwd]";// Choose both name and pwd Attribute user Elements
//String xpath="//user[@name='Jack'][@pwd='1234']";// choice name='Jack' And pwd='1234' that user Elements
//String xpath="//user[@name='"+name+"'][@pwd='"+pwd+"']";// According to the input name and ped Look for that user---name Case sensitive
String xpath="//user[fn:lower-case(@name)='"+name+"'][@pwd='"+pwd+"']";// According to the input name and ped Look for that user---name Case insensitive
System.out.println(xpath);
List<Element> list = dom.selectNodes(xpath);
for(Element e:list){
System.out.println(e.getName());
List<Element> eList = e.selectNodes("//contact/name");
for(Element e2:eList){
System.out.println(e2.getText());
}
}
}
}

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Familiar with memory]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121125355144t.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云