Xml的4种解析 及增删改泛型实现XML的4种解析
书写xml文件
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>书名</name>
<author>作者</author>
<year>年份</year>
</book>
<book>
<name>安徒生童话</name>
<author>安徒生</author>
<year>2004</year>
</book>
</books>
书写存储解析的类
public class Book {
private String name;
private String author;
private String year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Book(String name, String author, String year) {
super();
this.name = name;
this.author = author;
this.year = year;
}
public Book() {
super();
}
@Override
public String toString() {
return "Book [name=" + name + ", author=" + author + ", year=" + year + "]";
}
}
SAX解析
public class SAX extends DefaultHandler {
String s = "";
ArrayList<Book> arr = new ArrayList<Book>();
Book b = null;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("name")) {
b = new Book();
b.setName(s);
} else if (qName.equals("author")) {
b.setAuthor(s);
} else if (qName.equals("year")) {
b.setYear(s);
arr.add(b);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
s = new String(ch, start, length);
}
public static void main(String[] args) throws Exception {
SAXParserFactory sParserFactory = SAXParserFactory.newInstance();
SAXParser parser = sParserFactory.newSAXParser();
SAX handler = new SAX();
parser.parse("F://eclipse_workspace//javaOO//books.xml", handler);
System.out.println(handler.arr);
}
}
JDOM解析
SAXBuilder sb=new SAXBuilder();
Document d = sb.build("F://eclipse_workspace//javaOO//books.xml");
Element rootElement = d.getRootElement();
List<Element> children = rootElement.getChildren();
for (Element element : children) {
List<Element> children2 = element.getChildren();
for (Element element2 : children2) {
System.out.println(element2.getValue());
}
}
DOM4J解析
public class Dom4JTest {
public static void main(String[] args) throws DocumentException {
SAXReader sr=new SAXReader();
Document read = sr.read("F://eclipse_workspace//javaOO//books.xml");
Element rootElement = read.getRootElement();
Iterator elementIterator = rootElement.elementIterator();
while(elementIterator.hasNext())
{
Element next = (Element) elementIterator.next();
Iterator elementIterator2 = next.elementIterator();
while(elementIterator2.hasNext())
{
Element next2 = (Element) elementIterator2.next();
System.out.println(next2.getText());
}
}
}
}
Xml的增删改的实现方法
package com.yunhe.Readtxml;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
public class TestZengShanGai {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
updtNode2();
}
public static void deleteNode() throws SAXException, IOException, ParserConfigurationException, TransformerException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("src//com//text//books.xml");
NodeList all=doc.getChildNodes();
Node root=all.item(0);
System.out.println(root.getNodeName());
NodeList books=root.getChildNodes();
for(int i=0;i<books.getLength();i++)
{
Node book=books.item(i);
if("book".equals(book.getNodeName()))
{
Element el=(Element)book;
if(el.getAttribute("id").equals("101"))
{
System.out.println(el.getAttribute("id"));
el.getParentNode().removeChild(book);
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tran=tf.newTransformer();
DOMSource domSourse=new DOMSource(doc);
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");
StreamResult result=new StreamResult(new FileOutputStream("src//com//text//books.xml"));
tran.transform(domSourse, result);
}
}
}
}
public static void deleteNode2() throws ParserConfigurationException, SAXException, IOException, TransformerException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
db=dbf.newDocumentBuilder();
Document doc=db.parse("src//com//text//books.xml");
NodeList books=doc.getElementsByTagName("book");
for(int i=0;i<books.getLength();i++)
{
System.out.println(books.item(i).getNodeName());
Node book=books.item(i);
if("book".equals(book.getNodeName()))
{
Element el=(Element)book;
if(el.getAttribute("id").equals("101"))
{
System.out.println(el.getAttribute("id"));
el.getParentNode().removeChild(book);
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tran=tf.newTransformer();
DOMSource domSourse=new DOMSource(doc);
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");
StreamResult result=new StreamResult(new FileOutputStream("src//com//text//books.xml"));
tran.transform(domSourse, result);
}
}
}
}
public static void reviseNode() throws ParserConfigurationException, SAXException, IOException, TransformerException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("src//com//text//books.xml");
NodeList all=doc.getChildNodes();
Node root=all.item(0);
System.out.println(root.getNodeName());
NodeList books=root.getChildNodes();
for(int i=0;i<books.getLength();i++)
{
Node book=books.item(i);
if("book".equals(book.getNodeName()))
{
Element el=(Element)book;
if("102".equals(el.getAttribute("id")))
{
NodeList items=book.getChildNodes();
for(int j=0;j<items.getLength();j++)
{
Node item=items.item(j);
if("name".equals(item.getNodeName()))
{
item.setTextContent("张三丰");
}
if("author".equals(item.getNodeName()))
{
item.setTextContent("张三丰");
}
if("price".equals(item.getNodeName()))
{
item.setTextContent("张三丰");
}
}
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tran=tf.newTransformer();
DOMSource domSourse=new DOMSource(doc);
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");
StreamResult result=new StreamResult(new FileOutputStream("src//com//text//books.xml"));
tran.transform(domSourse, result);
}
}
}
}
public static void reviseNode2() throws ParserConfigurationException, SAXException, IOException, TransformerException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("src//com//text//books.xml");
NodeList all=doc.getChildNodes();
Node root=all.item(0);
System.out.println(root.getNodeName());
NodeList books=root.getChildNodes();
for(int i=0;i<books.getLength();i++)
{
Node book=books.item(i);
if("book".equals(book.getNodeName()))
{
Element el=(Element)book;
if("102".equals(el.getAttribute("id")))
{
NodeList prices=el.getElementsByTagName("price");
System.out.println("======"+prices.getLength());
for(int j=0;j<prices.getLength();j++)
{
Node price=prices.item(j);
price.setTextContent("15");
}
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tran=tf.newTransformer();
DOMSource domSourse=new DOMSource(doc);
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");
StreamResult result=new StreamResult(new FileOutputStream("src//com//text//books.xml"));
tran.transform(domSourse, result);
}
}
}
}
public static void updtNode() throws ParserConfigurationException, SAXException, IOException, TransformerException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("src//com//text//books.xml");
Element book=doc.createElement("book");
book.setAttribute("id", "101");
Element name=doc.createElement("name");
Text item=doc.createTextNode("AAA");
name.appendChild(item);
Element author=doc.createElement("author");
item=doc.createTextNode("BBB");
author.appendChild(item);
Element price=doc.createElement("price");
item=doc.createTextNode("CCC");
price.appendChild(item);
book.appendChild(name);
book.appendChild(author);
book.appendChild(price);
NodeList all=doc.getChildNodes();
Node root=all.item(0);
root.appendChild(book);
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tran=tf.newTransformer();
DOMSource domSourse=new DOMSource(doc);
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");
StreamResult result=new StreamResult(new FileOutputStream("src//com//text//books.xml"));
tran.transform(domSourse, result);
}
public static void updtNode2() throws ParserConfigurationException, SAXException, IOException, TransformerException
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse("src//com//text//books.xml");
Element book=doc.createElement("book");
book.setAttribute("id", "101");
Element name=doc.createElement("name");
name.setTextContent("盗墓笔记");
Element author=doc.createElement("author");
author.setTextContent("南派三叔");
Element price=doc.createElement("price");
price.setTextContent("35");
book.appendChild(name);
book.appendChild(author);
book.appendChild(price);
NodeList all=doc.getChildNodes();
Node root=all.item(0);
root.appendChild(book);
TransformerFactory tf=TransformerFactory.newInstance();
Transformer tran=tf.newTransformer();
DOMSource domSourse=new DOMSource(doc);
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");
StreamResult result=new StreamResult(new FileOutputStream("src//com//text//books.xml"));
tran.transform(domSourse, result);
}
}
利用泛型实现XML的4种解析
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.w3c.dom.NodeList;
public class XmlUtil {
public static <E> ArrayList<E> sax(Class<E> c,String uri)
{
E o;
ArrayList<E> arr = new ArrayList<E>();
return arr;
}
public static <E> ArrayList<E> Dom(Class<E> c,String uri)
{
E o;
ArrayList<E> arr = new ArrayList<E>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
org.w3c.dom.Document parse = db.parse(uri);
NodeList root = parse.getChildNodes();
for (int i = 0; i < root.getLength(); i++) {
NodeList childNodes = root.item(i).getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
if(childNodes.item(j).getNodeType()!=3)
{
o=c.newInstance();
NodeList childNodes2 = childNodes.item(j).getChildNodes();
for (int k = 0; k < childNodes2.getLength(); k++) {
Field field = null ;
if(childNodes2.item(k).getNodeType()!=3)
{
field = c.getDeclaredField(childNodes2.item(k).getNodeName());
field.setAccessible(true);
field.set(o,childNodes2.item(k).getFirstChild().getTextContent());
}
}
arr.add(o);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
public static <E> ArrayList<E> JDom(Class<E> c,String uri)
{
ArrayList<E> arr = new ArrayList<E>();
E o = null;
SAXBuilder sb=new SAXBuilder();
try {
org.jdom2.Document build = sb.build(uri);
org.jdom2.Element rootElement = build.getRootElement();
List<org.jdom2.Element> children = rootElement.getChildren();
for (org.jdom2.Element element : children) {
try {
o = c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
List<org.jdom2.Element> children2 = element.getChildren();
for (org.jdom2.Element element2 : children2) {
Field field = null;
try {
field = c.getDeclaredField(element2.getName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
field.setAccessible(true);
try {
field.set(o, element2.getValue());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
arr.add(o);
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return arr;
}
public <E> ArrayList<E> Dom4J(Class<E> c,String uri)
{
ArrayList<E> arr = new ArrayList<E>();
try {
SAXReader sr = new SAXReader();
Document d = sr.read(uri);
Element rootElement = d.getRootElement();
Iterator<?> ei = rootElement.elementIterator();
while (ei.hasNext()) {
E e = c.newInstance();
Element next = (Element) ei.next();
Iterator<?> elementIterator = next.elementIterator();
while (elementIterator.hasNext()) {
Element next1 = (Element) elementIterator.next();
Field field = c.getDeclaredField(next1.getName());
field.setAccessible(true);
field.set(e, next1.getStringValue());
}
arr.add(e);
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
public static void main(String[] args) throws MalformedURLException {
}
}