Java XML解析

一、SAX生成和解析XML文档

1、简介

 为解决DOM的问题,出现了SAX。 SAX ,事件驱动。当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。

 优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。

 缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了; 无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;

 使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;

 2、SAX解析XML步骤

(1)建立接口XmlDocument,规定解析类需要实现的功能;

代码:

package com.xml;

import java.util.List;

import com.xml.domain.Stuff;

public interface XmlDocument {
/**
* 建立XML文档
* @param fileName 文件全路径名称
*/
public void createXml(String fileName,List<Stuff> stuffList);
public void createXml(String fileName);
/**
* 解析XML文档
* @param fileName 文件全路径名称
*/
public void parserXml(String fileName);
}

(2)编写实现类SaxDemo

代码:

package com.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

import com.xml.domain.Employee;
import com.xml.domain.Manager;
import com.xml.domain.Stuff;

/**
*
* @2.SAX生成和解析XML文档
*/

public class SaxDemo implements XmlDocument {
final static String fileNmae = "F:\java\workspace\MyTest\src\com\xml\myXML.xml";

public static void main(String args[]) {
SaxDemo sax = new SaxDemo();
List<Stuff> stuffList = new ArrayList<Stuff>();
stuffList.add(new Manager("cxli", "male", 23, "10k", "hight"));
stuffList.add(new Manager("randy", "male", 23, "10k", "middle"));
stuffList.add(new Employee("fengzi", "male", 23, "6k"));
stuffList.add(new Employee("saoxing", "male", 23, "6k"));

sax.createXml(fileNmae, stuffList);
sax.parserXml(fileNmae);
}

//创建XML

public void createXml(String fileName, List<Stuff> stuffList) {
Result resultXml = null;
File xmlFile = new File(fileName);
if (xmlFile.exists()) {
xmlFile.delete();
}
try {
resultXml = new StreamResult(new FileOutputStream(fileName));
SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler th = sff.newTransformerHandler();
th.setResult(resultXml);

Transformer transformer = th.getTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // 编码格式是UTF-8
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 换行
AttributesImpl attr = new AttributesImpl();

th.startDocument();// 文档开始
th.startElement("", "", "stuffs", attr);
for (Stuff stuff : stuffList) {
if (stuff instanceof Manager) {
th.startElement("", "", "managers", attr);
writeElement(th, attr, stuff);
th.endElement("", "", "managers");
} else if (stuff instanceof Employee) {
th.startElement("", "", "employees", attr);
writeElement(th, attr, stuff);
th.endElement("", "", "employees");
}
}
th.endElement("", "", "stuffs");
th.endDocument(); // 文档结束
} catch (Exception e) {
e.printStackTrace();
}

}

//解析XML

public void parserXml(String fileName) {
SAXParserFactory saxfac = SAXParserFactory.newInstance();
try {
SAXParser saxparser = saxfac.newSAXParser();
InputStream is = new FileInputStream(fileName);
saxparser.parse(is, new MySAXHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void createXml(String fileName) {
}

public void writeElement(TransformerHandler th, AttributesImpl attr,Stuff stuff) throws SAXException {

if (stuff instanceof Manager) {
Manager manager = (Manager) stuff;
th.startElement("", "", "manager", attr);
th.startElement("", "", "name", attr);
th.characters(manager.getName().toCharArray(), 0, manager.getName().length());
th.endElement("", "", "name");
th.startElement("", "", "sex", attr);
th.characters(manager.getSex().toCharArray(), 0, manager.getSex().length());
th.endElement("", "", "sex");
th.startElement("", "", "age", attr);
th.characters(((manager.getAge()) + "").toCharArray(), 0, ((manager.getAge()) + "").length());
th.endElement("", "", "age");
th.startElement("", "", "salery", attr);
th.characters(manager.getSalery().toCharArray(), 0, manager.getSalery().length());
th.endElement("", "", "salery");
th.startElement("", "", "priority", attr);
th.characters(manager.getPriority().toCharArray(), 0, manager.getPriority().length());
th.endElement("", "", "priority");
th.endElement("", "", "manager");

} else if (stuff instanceof Employee) {
Employee employee = (Employee) stuff;

th.startElement("", "", "employee", attr);
th.startElement("", "", "name", attr);
th.characters(employee.getName().toCharArray(), 0, employee.getName().length());
th.endElement("", "", "name");
th.startElement("", "", "sex", attr);
th.characters(employee.getSex().toCharArray(), 0, "male".length());
th.endElement("", "", "sex");
th.startElement("", "", "age", attr);
th.characters(((employee.getAge()) + "").toCharArray(), 0,((employee.getAge()) + "").length());
th.endElement("", "", "age");
th.startElement("", "", "salery", attr);
th.characters(employee.getSalery().toCharArray(), 0, employee.getSalery().length());
th.endElement("", "", "salery");
th.endElement("", "", "employee");

}

}

public void dealWithNode(String fileName, String nodeName) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
org.w3c.dom.Document document = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
document = builder.parse(new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
NodeList links = document.getElementsByTagName(nodeName);
for (int i = 1; i < links.getLength() - 1; i++) {
}
}
}

class MySAXHandler extends DefaultHandler {
public boolean hasAttribute = false;
public Attributes attributes = null;
public FileOutputStream fos = null;
public StringBuilder sb = null;
File myXMLFile = null;

public void startDocument() throws SAXException {
System.out.println("文档开始打印了");
}

public void endDocument() throws SAXException {
System.out.println("文档打印结束了");
}

public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (qName.equals("employees")) {
myXMLFile = new File(
"F:\java\workspace\MyTest\src\com\xml\employees.xml");
sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='UTF-8'?> ");
} else if (qName.equals("managers")) {
myXMLFile = new File(
"F:\java\workspace\MyTest\src\com\xml\managers.xml");
sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='UTF-8'?> ");
}
dealWithStartElement(qName);

if (attributes.getLength() > 0) {
this.attributes = attributes;
this.hasAttribute = true;
}
}

public void endElement(String uri, String localName, String qName)throws SAXException {
dealWithEndElement(qName);
if (qName.equals("employees") || qName.equals("managers")) {
try {
fos = new FileOutputStream(myXMLFile);
fos.write(sb.toString().getBytes());
} catch (Exception e1) {
e1.printStackTrace();
}
}
if (hasAttribute && (attributes != null)) {
for (int i = 0; i < attributes.getLength(); i++) {
System.out.print(attributes.getValue(0));
}
}

}

public void characters(char[] ch, int start, int length)throws SAXException {
System.out.print(new String(ch, start, length));
String character = new String(ch, start, length);
if (!(character.equals(" "))) {
sb.append((new String(ch, start, length)));
}
}

public void dealWithStartElement(String qName) {
if ((qName.equals("employees")) || (qName.equals("managers"))|| (qName.equals("employee")) || (qName.equals("manager"))) {
System.out.print("<" + qName + ">");
sb.append("<" + qName + ">" + " ");
}
if ((qName.equals("name")) || (qName.equals("sex"))|| (qName.equals("age")) || (qName.equals("salery"))|| (qName.equals("priority"))) {
System.out.print("<" + qName + ">");
sb.append("<" + qName + ">");
}
}

public void dealWithEndElement(String qName) {
if ((qName.equals("employees")) || (qName.equals("managers"))
|| (qName.equals("employee")) || (qName.equals("manager"))
|| (qName.equals("name")) || (qName.equals("sex"))
|| (qName.equals("age")) || (qName.equals("salery"))
|| (qName.equals("priority"))) {
System.out.print("</" + qName + ">");
sb.append("</" + qName + ">" + " ");
}
}
}

(3)相关前期准备工作

 最后生成的XML如下:

<?xml version="1.0" encoding="UTF-8"?>
<stuffs>
<managers>
<manager>
<name>cxli</name>
<sex>male</sex>
<age>23</age>
<salery>10k</salery>
<priority>hight</priority>
</manager>
<manager>
<name>randy</name>
<sex>male</sex>
<age>23</age>
<salery>10k</salery>
<priority>middle</priority>
</manager>
</managers>
<employees>
<employee>
<name>fengzi</name>
<sex>male</sex>
<age>23</age>
<salery>6k</salery>
</employee>
<employee>
<name>saoxing</name>
<sex>male</sex>
<age>23</age>
<salery>6k</salery>
</employee>
</employees>
</stuffs>

从跟上面的XML,我们可以看出,存储的信息stuff信息,具体分为manager和employee。因此,我们可以讲XML中存储的信息抽象为JAVA类,即Manager类和Employee类;他们都实现了接口Stuff。代码如下:

Stuff接:

package com.xml.domain;
/**
*
* @author 风子
* 员工接口
*
*/
public interface Stuff {}

Manager类:

package com.xml.domain;

public class Manager implements Stuff{
private String name;
private String sex;
private int age;
private String salery;
private String priority;

public Manager(String name, String sex, int age, String salery,String priority) {
this.name = name;
this.sex = sex;
this.age = age;
this.salery = salery;
this.priority = priority;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getSalery() {
return salery;
}

public void setSalery(String salery) {
this.salery = salery;
}

public String getPriority() {
return priority;
}

public void setPriority(String priority) {
this.priority = priority;
}

}

Employee类:

package com.xml.domain;

public class Employee implements Stuff{
private String name;
private String sex;
private int age;
private String salery;
public Employee(String name, String sex, int age, String salery) {
this.name = name;
this.sex = sex;
this.age = age;
this.salery = salery;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSalery() {
return salery;
}
public void setSalery(String salery) {
this.salery = salery;
}

}

二、DOM生成和解析XML文档

1、简介

 DOM生成和解析XML文档为XML 文档的已解析版本定义了一组接口。

 解析器读入整个文档, 然后构建一个驻留内存的树结构, 然后代码就可以使用DOM 接口来操作这个树结构。

 优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;

 缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;

 使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。

2、代码

 DOM解析xml所需的前期工作和SAX解析一样,这里不再赘述。

package com.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.TransformerConfigurationException;
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.xml.sax.SAXException;

import com.xml.domain.Employee;
import com.xml.domain.Manager;
import com.xml.domain.Stuff;


public class DomDemo implements XmlDocument {
private Document document;
static List<Stuff> StuffList = new ArrayList<Stuff>();
final static String fileNmae = "F:\java\workspace\MyTest\src\com\xml\myXML_DOM.xml";

public static void main(String args[]) {
DomDemo Dom = new DomDemo();

//解析前的相关初始化工作
Dom.init();

//实例化相关类,作为形成XML时的数据
List<Stuff> stuffList = Dom.creatDatas();

//形成XML,stuffList为类的集合
Dom.createXml(fileNmae, stuffList);

//解析XML,并将解析后的数据重新封装成相应的对象
Dom.parserXml(fileNmae);

//展示解析后的对象,这里的数据和前期构造的数据保持一致
Dom.showDatas(StuffList);
}

//整个过程分为:创建类,类应于XML保持一致(类名对应根节点,类的属性对应子节点)——>构造数据(实例化相关类)——>用构造的数据形成XML——>解析XML,并将解析的数据重新封装成对象

public void init() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.document = builder.newDocument();
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
}
}

public List<Stuff> creatDatas() {
List<Stuff> stuffList = new ArrayList<Stuff>();
stuffList.add(new Manager("cxli", "male", "23","10k", "hight"));
stuffList.add(new Employee("saoxing", "male", "23", "6k"));
stuffList.add(new Manager("randy", "male", "23", "10k", "middle"));
stuffList.add(new Employee("fengzi", "male", "23", "6k"));

return stuffList;
}

public void showDatas(List<Stuff> stuffList){
for(Stuff stuff:stuffList)
{
if(stuff instanceof Manager)
{
Manager manager = (Manager)stuff;
System.out.println("Manager的相关信息:");
System.out.println("name:"+manager.getName());
System.out.println("sex:"+manager.getSex());
System.out.println("age:"+manager.getAge());
System.out.println("salery:"+manager.getSalery());
System.out.println("priority:"+manager.getPriority());
}
else if(stuff instanceof Employee)
{
Employee employee = (Employee)stuff;
System.out.println("Employee的相关信息:");
System.out.println("name:"+employee.getName());
System.out.println("sex:"+employee.getSex());
System.out.println("age:"+employee.getAge());
System.out.println("salery:"+employee.getSalery());
}
}
}
@Override
public void createXml(String fileName, List<Stuff> stuffList) {
Element root = this.document.createElement("stuffs");
this.document.appendChild(root);
Element managers = null;
Element employees = null;
int i = 0;
int j = 0;
for (Stuff stuff : stuffList) {
if (stuff instanceof Manager) {
if (i < 1) {
managers = this.document.createElement("managers");
i++;
root.appendChild(managers);
}
managers.appendChild(writeElement(stuff));
} else if (stuff instanceof Employee) {
if (j < 1) {
employees = this.document.createElement("employees");
j++;
root.appendChild(employees);
}
employees.appendChild(writeElement(stuff));
}
}
TransformerFactory tf = TransformerFactory.newInstance();
try {
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
File xmlFile = new File(fileName);
if (xmlFile.exists()) {
xmlFile.delete();
}
PrintWriter pw = new PrintWriter(new FileOutputStream(xmlFile));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
System.out.println("生成XML文件成功!");
} catch (TransformerConfigurationException e) {
System.out.println(e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (TransformerException e) {
System.out.println(e.getMessage());
}
}

public Element writeElement(Stuff stuff) {
Element returnElement = null;
if (stuff instanceof Manager) {
Manager amanager = (Manager) stuff;
Element manager = this.document.createElement("manager");
Element name = this.document.createElement("name");
name.appendChild(this.document.createTextNode(amanager.getName()));
manager.appendChild(name);
Element sex = this.document.createElement("sex");
sex.appendChild(this.document.createTextNode(amanager.getSex()));
manager.appendChild(sex);
Element age = this.document.createElement("age");
age.appendChild(this.document.createTextNode(amanager.getAge()));
manager.appendChild(age);
Element salery = this.document.createElement("salery");
salery.appendChild(this.document.createTextNode(amanager.getSalery()));
manager.appendChild(salery);
Element priority = this.document.createElement("priority");
priority.appendChild(this.document.createTextNode(amanager.getPriority()));
manager.appendChild(priority);
returnElement = manager;
} else if (stuff instanceof Employee) {
Employee aemployee = (Employee) stuff;
Element employee = this.document.createElement("employee");
Element name = this.document.createElement("name");
name.appendChild(this.document.createTextNode(aemployee.getName()));
employee.appendChild(name);
Element sex = this.document.createElement("sex");
sex.appendChild(this.document.createTextNode(aemployee.getSex()));
employee.appendChild(sex);
Element age = this.document.createElement("age");
age.appendChild(this.document.createTextNode(aemployee.getAge()));
employee.appendChild(age);
Element salery = this.document.createElement("salery");
salery.appendChild(this.document.createTextNode(aemployee.getSalery()));
employee.appendChild(salery);
returnElement = employee;
}
return returnElement;
}

public void createXml(String fileName) {
}

@SuppressWarnings("unchecked")
public void parserXml(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(fileName);
NodeList fathernodelist = document.getChildNodes();
Manager managerClone = null;
Employee employeeClone = null;
Map map = null;

for (int i = 0; i < fathernodelist.getLength(); i++) {
Node fathernode = fathernodelist.item(i);
NodeList firstchildnodelist = fathernode.getChildNodes();

for (int j = 0; j < firstchildnodelist.getLength(); j++) {
Node firstchildnode = firstchildnodelist.item(j);
NodeList secondchildnodelist = firstchildnode.getChildNodes();

for (int k = 0; k < secondchildnodelist.getLength(); k++) {
Node secondchildnode = secondchildnodelist.item(k);
if (secondchildnode.getNodeName().equals("manager")){
map = new HashMap<String, String>();
managerClone = new Manager();
NodeList metaChild = secondchildnode.getChildNodes();
for (int m = 0; m < metaChild.getLength(); m++) {
if (metaChild.item(m) instanceof Element){
map.put(metaChild.item(m).getNodeName(), metaChild.item(m).getTextContent());
}
}
managerClone.setName(map.get("name").toString());
managerClone.setSex(map.get("sex").toString());
managerClone.setAge(map.get("age").toString());
managerClone.setSalery(map.get("salery").toString());
managerClone.setPriority(map.get("priority").toString());
StuffList.add(managerClone);
} else if (secondchildnode.getNodeName().equals("employee")) {
map = new HashMap<String, String>();
employeeClone = new Employee();
NodeList metaChild = secondchildnode.getChildNodes();
for (int m = 0; m < metaChild.getLength(); m++) {
if (metaChild.item(m) instanceof Element){
map.put(metaChild.item(m).getNodeName(), metaChild.item(m).getTextContent());
}
}
employeeClone.setName(map.get("name").toString());
employeeClone.setSex(map.get("sex").toString());
employeeClone.setAge(map.get("age").toString());
employeeClone.setSalery(map.get("salery").toString());
StuffList.add(employeeClone);
}
}
}
}
System.out.println("-----------------------");
System.out.println("解析完毕!");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

 三、Dom4J解析XML

1、简介

 DOM4J生成和解析XML文档DOM4J 是一个非常非常优秀的Java XML API,

 具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。

 如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写

 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。

 2、代码

 Dom4J解析XML的前期工作和其他的一样,这里不再赘述。

package com.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.xml.domain.Employee;
import com.xml.domain.Manager;
import com.xml.domain.Stuff;


public class Dom4jDemo implements XmlDocument {
static List<Stuff> stuffList = new ArrayList<Stuff>();
final static String fileNmae = "F:\java\workspace\MyTest\src\com\xml\myXML_DOM4J.xml";

public static void main(String[] args) {
Dom4jDemo Dom4j = new Dom4jDemo();
List<Stuff>stuffList_1 = Dom4j.creatDatas();
Dom4j.createXml(fileNmae, stuffList_1);
Dom4j.parserXml(fileNmae);
Dom4j.showDatas(stuffList);
}

public List<Stuff> creatDatas() {
List<Stuff> stuffList_1 = new ArrayList<Stuff>();
stuffList_1.add(new Manager("cxli", "male", "23", "10k", "hight"));
stuffList_1.add(new Employee("saoxing", "male", "23", "6k"));
stuffList_1.add(new Manager("randy", "male", "23", "10k", "middle"));
stuffList_1.add(new Employee("fengzi", "male", "23", "6k"));

return stuffList_1;
}

public void showDatas(List<Stuff> stuffList){
for(Stuff stuff:stuffList)
{
if(stuff instanceof Manager)
{
Manager manager = (Manager)stuff;
System.out.println("Manager的相关信息:");
System.out.println("name:"+manager.getName());
System.out.println("sex:"+manager.getSex());
System.out.println("age:"+manager.getAge());
System.out.println("salery:"+manager.getSalery());
System.out.println("priority:"+manager.getPriority());
}
else if(stuff instanceof Employee)
{
Employee employee = (Employee)stuff;
System.out.println("Employee的相关信息:");
System.out.println("name:"+employee.getName());
System.out.println("sex:"+employee.getSex());
System.out.println("age:"+employee.getAge());
System.out.println("salery:"+employee.getSalery());
}
}
}

public void createXml(String fileName) {
}

@SuppressWarnings("unchecked")
public void parserXml(String fileName) {
File inputXml = new File(fileName);
SAXReader saxReader = new SAXReader();
Manager amanager = null;
Employee aemployee = null;
Map map = new HashMap<String, String>();
try {
Document document = saxReader.read(inputXml);
Element stuffs = document.getRootElement();
for (Iterator i = stuffs.elementIterator(); i.hasNext();) {
Element stuff = (Element) i.next();
if (stuff.getName().equals("managers")) {
for (Iterator j = stuff.elementIterator(); j.hasNext();) {
Element manaager = (Element) j.next();
amanager = new Manager();
for (Iterator m = manaager.elementIterator(); m.hasNext();) {
Element node = (Element) m.next();
map.put(node.getName(),node.getText());
}
amanager.setName((map.get("name")).toString());
amanager.setAge((map.get("age")).toString());
amanager.setSex((map.get("sex")).toString());
amanager.setSalery((map.get("salery")).toString());
amanager.setPriority((map.get("priority")).toString());
stuffList.add(amanager);
}

} else if (stuff.getName().equals("employees")) {
for (Iterator j = stuff.elementIterator(); j.hasNext();) {
Element employee = (Element) j.next();
aemployee = new Employee();
for (Iterator m = employee.elementIterator(); m.hasNext();) {
Element node = (Element) m.next();
map.put(node.getName(),node.getText());
}
aemployee.setName((map.get("name")).toString());
aemployee.setAge((map.get("age")).toString());
aemployee.setSex((map.get("sex")).toString());
aemployee.setSalery((map.get("salery")).toString());
stuffList.add(aemployee);
}
}
}
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
System.out.println("-----------------");
System.out.println("XML解析成功!");
}

@Override
public void createXml(String fileName, List<Stuff> stuffList) {
Document document = DocumentHelper.createDocument();
Element stuffs = document.addElement("Stuffs");
Element managers = stuffs.addElement("managers");
Element employees = stuffs.addElement("employees");
Manager manager = null;
Employee employee = null;
for (Stuff stuff : stuffList) {
if (stuff instanceof Manager) {
manager = (Manager) stuff;
writeManagerElement(manager, managers);
} else if (stuff instanceof Employee) {
employee = (Employee) stuff;
writeEmployeerElement(employee, employees);
}
}
try {
Writer fileWriter = new FileWriter(fileName);
XMLWriter xmlWriter = new XMLWriter(fileWriter);
xmlWriter.write(document);
xmlWriter.close();
System.out.println("XML生成成功!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

private void writeManagerElement(Manager amanager, Element managers) {
Element manager = managers.addElement("manager");
Element name = manager.addElement("name");
name.setText(amanager.getName());
Element sex = manager.addElement("sex");
sex.setText(amanager.getSex());
Element age = manager.addElement("age");
age.setText(amanager.getAge());
Element salery = manager.addElement("salery");
salery.setText(amanager.getSalery());
Element priority = manager.addElement("priority");
priority.setText(amanager.getPriority());
}

private void writeEmployeerElement(Employee aemployee, Element managers) {
Element employee = managers.addElement("employee");
Element name = employee.addElement("name");
name.setText(aemployee.getName());
Element sex = employee.addElement("sex");
sex.setText(aemployee.getSex());
Element age = employee.addElement("age");
age.setText(aemployee.getAge());
Element salery = employee.addElement("salery");
salery.setText(aemployee.getSalery());
}
}

四、JDom解析XML

 1、简介

 为减少DOM、SAX的编码量,出现了JDOM;

 优点:20-80原则,极大减少了代码量。

 使用场合:要实现的功能简单,如解析、创建等,

 但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。

2、代码

JDom解析XML的前期准备和其他相同,这里不再赘述;

package com.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import com.xml.domain.Employee;
import com.xml.domain.Manager;
import com.xml.domain.Stuff;


public class JDomDemo implements XmlDocument {
static List<Stuff> StuffList = new ArrayList<Stuff>();
final static String fileNmae = "F:\java\workspace\MyTest\src\com\xml\myXML_JDOM.xml";

public static void main(String[] args) {
JDomDemo JDom = new JDomDemo();

//构造数据,这里的数据封装在java类中
List<Stuff> stuffList_1 = JDom.creatDatas();

//用构造的数据生成XML
JDom.createXml(fileNmae, stuffList_1);

//用JDom解析XML
JDom.parserXml(fileNmae);

//将解析得到的数据重新封装成类,并展示出来
JDom.showDatas(StuffList);
}

public List<Stuff> creatDatas() {
List<Stuff> stuffList_1 = new ArrayList<Stuff>();
stuffList_1.add(new Manager("cxli", "male", "23", "10k", "hight"));
stuffList_1.add(new Employee("saoxing", "male", "23", "6k"));
stuffList_1.add(new Manager("randy", "male", "23", "10k", "middle"));
stuffList_1.add(new Employee("fengzi", "male", "23", "6k"));

return stuffList_1;
}

public void showDatas(List<Stuff> stuffList) {
for (Stuff stuff : stuffList) {
if (stuff instanceof Manager) {
Manager manager = (Manager) stuff;
System.out.println("Manager的相关信息:");
System.out.println("name:" + manager.getName());
System.out.println("sex:" + manager.getSex());
System.out.println("age:" + manager.getAge());
System.out.println("salery:" + manager.getSalery());
System.out.println("priority:" + manager.getPriority());
} else if (stuff instanceof Employee) {
Employee employee = (Employee) stuff;
System.out.println("Employee的相关信息:");
System.out.println("name:" + employee.getName());
System.out.println("sex:" + employee.getSex());
System.out.println("age:" + employee.getAge());
System.out.println("salery:" + employee.getSalery());
}
}
}

public void createXml(String fileName) {
}

@Override
public void createXml(String fileName, List<Stuff> stuffList) {
Document document;
Element root;
root = new Element("stuffs");
document = new Document(root);
Element managers = new Element("managers");
Element employees = new Element("employees");
root.addContent(managers);
root.addContent(employees);
for (Stuff stuff : stuffList) {
if (stuff instanceof Manager) {
managers.addContent(writeElement(stuff));
} else if (stuff instanceof Employee) {
employees.addContent(writeElement(stuff));
}
}
XMLOutputter XMLOut = new XMLOutputter();
try {
XMLOut.output(document, new FileOutputStream(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private Element writeElement(Stuff stuff) {
Element returnElement = null;
if (stuff instanceof Manager) {
Manager amanager = (Manager) stuff;
Element manager = new Element("manager");
Element name = new Element("name");
name.setText(amanager.getName());
manager.addContent(name);
Element sex = new Element("sex");
sex.setText(amanager.getSex());
manager.addContent(sex);
Element age = new Element("age");
age.setText(amanager.getAge());
manager.addContent(age);
Element salery = new Element("salery");
salery.setText(amanager.getSalery());
manager.addContent(salery);
Element priority = new Element("priority");
priority.setText(amanager.getPriority());
manager.addContent(priority);
returnElement = manager;
} else if (stuff instanceof Employee) {
Employee aemployee = (Employee) stuff;
Element employee = new Element("manager");
Element name = new Element("name");
name.setText(aemployee.getName());
employee.addContent(name);
Element sex = new Element("sex");
sex.setText(aemployee.getSex());
employee.addContent(sex);
Element age = new Element("age");
age.setText(aemployee.getAge());
employee.addContent(age);
Element salery = new Element("salery");
salery.setText(aemployee.getSalery());
employee.addContent(salery);
returnElement = employee;
}
return returnElement;
}

@SuppressWarnings("unchecked")
public void parserXml(String fileName) {
SAXBuilder builder = new SAXBuilder(false);
Manager managerClone = null;
Employee employeeClone = null;
Map map = null;
try {
Document document = builder.build(fileName);
Element stuffs = document.getRootElement();
Element employees = stuffs.getChild("employees");
List employee = employees.getChildren();
for (int i = 0; i < employee.size(); i++) {
map = new HashMap<String, String>();
employeeClone = new Employee();
Element aemployee = (Element) employee.get(i);
List employeeInfo = aemployee.getChildren();
for (int j = 0; j < employeeInfo.size(); j++) {
map.put(((Element) employeeInfo.get(j)).getName(),
((Element) employeeInfo.get(j)).getValue());
}
employeeClone.setName(map.get("name").toString());
employeeClone.setSex(map.get("sex").toString());
employeeClone.setAge(map.get("age").toString());
employeeClone.setSalery(map.get("salery").toString());
StuffList.add(employeeClone);
}

Element managers = stuffs.getChild("managers");
List manager = managers.getChildren();
for (int i = 0; i < manager.size(); i++) {
map = new HashMap<String, String>();
managerClone = new Manager();
Element amanager = (Element) manager.get(i);
List managerInfo = amanager.getChildren();
for (int j = 0; j < managerInfo.size(); j++) {
map.put(((Element) managerInfo.get(j)).getName(),
((Element) managerInfo.get(j)).getValue());
}
managerClone.setName(map.get("name").toString());
managerClone.setSex(map.get("sex").toString());
managerClone.setAge(map.get("age").toString());
managerClone.setSalery(map.get("salery").toString());
managerClone.setPriority(map.get("priority").toString());
StuffList.add(managerClone);
}
} catch (JDOMException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}

}
}

 

原文地址:https://www.cnblogs.com/FZ1314/p/5874116.html