目录
一,xml简介
XML(EXtensible Markup Language):可扩展标记语言XML 是一种很像HTML的标记语言。
XML 的设计宗旨是传输数据,而不是显示数据。
XML 标签没有被预定义。您需要自行定义标签。
XML 是 W3C 的推荐标准。
XML 和 HTML 之间的差异
XML 和 HTML 为不同的目的而设计:XML 被设计用来传输和存储数据,其焦点是数据的内容。
HTML 被设计用来显示数据,其焦点是数据的外观。
文档结构:
每个XML文档有且只有一个根元素。
根元素的特点如下:
根元素是一个完全包括文档中其他所有元素的元素。
根元素的开始标签要放在所有其他元素的开始标签之前。
根元素的结束标签要放在所有其他元素的结束标签之后
特殊字符:
<?xml version="1.0" encoding="utf-8" ?>
<members>
<member>
<name>王者荣耀</name>
<vip>vip1000</vip>
<passward>000000</passward>
<jifen>1000</jifen>
</member>
<member>
<name>王者荣耀</name>
<vip>vip1000</vip>
<passward>000000</passward>
<jifen>1000</jifen>
</member>
</members>
二,解析xml
DOM解析
org.w3c.dom包中的常用接口
Document接口:Document对象代表整个XML文档,它也是对XML文档进行操作的
点Document接口继承自Node接口
常用方法:
NodeList接口:包含了一个或者多个节点的列表。
Element接口:代表XML文档中的标签元素。
Element接口继承自Node,也是Node最主要的子对象。在标签中可以包含属性。
DOM读取XML的步骤
1.创建解析器工厂对象(DocumentBuilderFactory)。
2.由解析器工厂对象创建解析器对象(DocumentBuilder)。
3.由解析器对象对指定XML文件进行解析,构建相应DOM树,创建Document对象。
4.以Document对象为起点对DOM树的节点进行增删改查操作使用
使用DOM保存XML文档
1.创建转换器工厂对象(TransformerFactory)。
2.由转换器工厂对象创建转换器对象(Transformer)。
3.创建DOMSource对象(DOMSource)。
4.由转换器对象设置输出格式(setOutputProperty方法)。
5.创建StreamResult对象(包含保存文件的信息)。
6.将XML保存到指定文件中(transform方法)。
例:
<?xml version="1.0" encoding="utf-8" ?>
<members>
<member>
<name>王者荣耀</name>
<vip>vip1000</vip>
<passward>000000</passward>
<jifen>1000</jifen>
</member>
<member>
<name>王者荣耀</name>
<vip>vip1000</vip>
<passward>000000</passward>
<jifen>1000</jifen>
</member>
</members>
package com.bdqn.lianxi.xml;
import lombok.Data;
@Data
public class Book {
private int id;
private String author;
private String titile;
private String description;
}
package com.bdqn.lianxi.xml;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
public class DomUtil {
public static Document createDocument(String path){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
File file = new File(path);
document = builder.parse(file);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.err.println("文件不存在");
} catch (SAXException e) {
e.printStackTrace();
}
return document;
}
public static void saveXml(Node node, String path){
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = factory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource domSource = new DOMSource(node);
StreamResult streamResult = new StreamResult(path);
try {
transformer.transform(domSource,streamResult);
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
package com.bdqn.lianxi.xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.util.List;
public class BookDao {
private List<Book> bookList = new ArrayList<>();
private static final String PATH = "day01\\zsgc.xml";
public void load(){
Document document = DomUtil.createDocument(PATH);
NodeList nodeList = document.getElementsByTagName("book");
Book book = null;
for(int i=0;i<nodeList.getLength();i++){
book = new Book();
Node node = nodeList.item(i);
Element element = (Element)node;
int id = Integer.parseInt(element.getAttribute("id"));
book.setId(id);
NodeList childNodeList = node.getChildNodes();
for(int j = 0;j<childNodeList.getLength();j++){
Node childNode = childNodeList.item(j);
String nodeName = childNode.getNodeName();
if("author".equals(nodeName)){
book.setAuthor(childNode.getTextContent());
}else if("title".equals(nodeName)){
book.setTitile(childNode.getTextContent());
}else if("description".equals(nodeName)){
book.setDescription(childNode.getTextContent());
}
}
bookList.add(book);
}
}
public void print(){
if(bookList!=null && !bookList.isEmpty()){
System.out.println("序号\t\t书名\t\t作者\t\t简介");
bookList.forEach(book -> {
System.out.println(book.getId()+"\t\t"+book.getTitile()+
"\t\t"+book.getAuthor()+"\t\t"+book.getDescription());
});
}
}
public void add(Book book){
Document document = DomUtil.createDocument(PATH);
Element element = document.createElement("book");
element.setAttribute("id",String.valueOf(book.getId()));
Element author = document.createElement("author");
author.setTextContent(book.getAuthor());
Element title = document.createElement("title");
title.setTextContent(book.getTitile());
Element description = document.createElement("description");
description.setTextContent(book.getDescription());
element.appendChild(author);
element.appendChild(title);
element.appendChild(description);
Element root = document.getDocumentElement();
root.appendChild(element);
DomUtil.saveXml(root,PATH);
}
public void modify(){
Document document = DomUtil.createDocument(PATH);
NodeList nodeList = document.getElementsByTagName("book");
Book book = null;
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element element = (Element)node;
int id = Integer.parseInt(element.getAttribute("id"));
if(id==101){
NodeList childNodeList = node.getChildNodes();
for(int j = 0;j<childNodeList.getLength();j++){
Node childNode = childNodeList.item(j);
String nodeName = childNode.getNodeName();
if("author".equals(nodeName)){
childNode.setTextContent("李刚");
}
}
}
}
DomUtil.saveXml(document.getDocumentElement(),PATH);
}
public void delete(){
Document document = DomUtil.createDocument(PATH);
NodeList nodeList = document.getElementsByTagName("book");
Book book = null;
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element element = (Element)node;
int id = Integer.parseInt(element.getAttribute("id"));
if(id == 103){
document.getDocumentElement().removeChild(element);
}
}
DomUtil.saveXml(document.getDocumentElement(),PATH);
}
}
package com.bdqn.lianxi.xml;
public class TestBook {
public static void main(String[] args) {
BookDao bookDao = new BookDao();
bookDao.delete();
bookDao.load();
bookDao.print();
/* Book book = new Book();
book.setId(103);
book.setAuthor("路遥");
book.setTitile("平凡的世界");
book.setDescription("讲述孙少平和孙少安的故事");
bookDao.add(book);*/
//bookDao.modify();
}
}
DOM4j解析
需要一个导入一个jar包
@Data
public class Book {
private String id;
private String author;
private String titile;
private String description;
}
public class BookDao {
private List<Book> bookList = new ArrayList<>();
public void showInfo(){
Document document = DomUtil.createDocument();
Element books = document.getRootElement();
Iterator rootIte = books.elementIterator();
Book book = null;
while (rootIte.hasNext()){
book = new Book();
Element bookEle = (Element) rootIte.next();
book.setId(bookEle.attributeValue("id"));
Iterator childIte = bookEle.elementIterator();
while (childIte.hasNext()){
Element childEle = (Element) childIte.next();
String eleName = childEle.getName();
switch (eleName){
case "author":
book.setAuthor(childEle.getText());
break;
case "title":
book.setTitile(childEle.getText());
break;
case "description":
book.setDescription(childEle.getText());
break;
}
}
bookList.add(book);
}
}
public void print(){
showInfo();
if(bookList!=null && !bookList.isEmpty()){
bookList.forEach(book -> {
System.out.println(book);
});
}
}
public void add(){
Document document = DomUtil.createDocument();
Element books = document.getRootElement();
Element book = books.addElement("book");
book.addAttribute("id","103");
Element author = book.addElement("author");
author.setText("刘慈欣");
Element title = book.addElement("title");
title.setText("三体");
Element description = book.addElement("description");
description.setText("消灭人类暴政,世界属于三体");
try {
DomUtil.save(document,"books-bak.xml");
} catch (IOException e) {
e.printStackTrace();
}
}
public void update(){
Document document = DomUtil.createDocument();
Element books = document.getRootElement();
Iterator rootIte = books.elementIterator();
while (rootIte.hasNext()){
Element bookEle = (Element) rootIte.next();
Iterator childIte = bookEle.elementIterator();
String id = bookEle.attributeValue("id");
if("101".equals(id)){
while (childIte.hasNext()){
Element childEle = (Element) childIte.next();
String eleName = childEle.getName();
if("author".equals(eleName)){
childEle.setText("老张");
}
}
}
}
try {
DomUtil.save(document,"books-update.xml");
} catch (IOException e) {
e.printStackTrace();
}
}
public void delete(){
Document document = DomUtil.createDocument();
Element books = document.getRootElement();
Iterator rootIte = books.elementIterator();
while (rootIte.hasNext()){
Element bookEle = (Element) rootIte.next();
String id = bookEle.attributeValue("id");
if("102".equals(id)){
bookEle.getParent().remove(bookEle);
}
}
try {
DomUtil.save(document,"books-delete.xml");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class DomUtil {
public static Document createDocument(){
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(new File("books.xml"));
} catch (DocumentException e) {
e.printStackTrace();
}
return document;
}
public static void save(Document document,String path) throws IOException {
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
XMLWriter xmlWriter = new XMLWriter(new FileWriter(path),outputFormat);
xmlWriter.write(document);
xmlWriter.close();
}
}
public class TestBook {
public static void main(String[] args) {
BookDao bookDao = new BookDao();
//bookDao.showInfo();
//bookDao.print();
//bookDao.add();
//bookDao.update();
bookDao.delete();
}
}