xml的四种解析方式实例
一、DOM(Document Object Model)解析方式
在应用程序中,基于DOM的xml分析器将xml文档解析成一个对象模型的集合(通常称DOM树),应用程序正是通过对这个对象模型的操作,来实现对xml数据的操作.通过DOM接口应用程序可以在任何时候访问xml文档的任何一部分数据.
DOM接口提供了一种通过分层对象模型来访问XML文档信息的方式,这些分层对象模型依据XML的文档结构形成了一棵节点树。无论XML文档中所描述的是什么类型的信息,即便是制表数据、项目列表或一个文档,利用DOM所生成的模型都是节点树的形式。也就是说,DOM强制使用树模型来访问XML文档中的信息。由于XML本质上就是一种分层结构,所以这种描述方法是相当有效的。
DOM树所提供的随机访问方式给应用程序带来了很大的灵活性,它可以任意控制xml文档中的内容。然而,由于DOM分析器把整个xml文档转换成DOM树放在了内存中,因此,当文档比较大或者数据比较复杂的时候,对内存的需求就比较高。而且对于结构复杂的树的遍历也是一项耗时的工作。所以DOM分析器对于机器性能要求比较高,实现效率不十分理想。不过,由于DOM分析器所采用的树结构的思想与xml文档的结构相吻合,同时鉴于随机访问所带来的方便,因此DOM分析器还是有着比较广泛的应用。
实例一:
package dom;import java.io.File;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;public class DomTest1
{public static void main(String[] args) throws Exception{// step 1: 获得dom解析器工厂(工作的作用是用于创建具体的解析器)DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();System.out.println("class name: " + dbf.getClass().getName());// step 2:获得具体的dom解析器DocumentBuilder db = dbf.newDocumentBuilder();System.out.println("class name: " + db.getClass().getName());// step3: 解析一个xml文档,获得Document对象(根结点)Document document = db.parse(new File("candidate.xml"));//文件路径可以是绝对路径也可以是相对路径NodeList list = document.getElementsByTagName("PERSON");for(int i = 0; i < list.getLength(); i++){Element element = (Element)list.item(i);String content = element.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue();System.out.println("name:" + content);content = element.getElementsByTagName("ADDRESS").item(0).getFirstChild().getNodeValue();System.out.println("address:" + content);content = element.getElementsByTagName("TEL").item(0).getFirstChild().getNodeValue();System.out.println("tel:" + content);content = element.getElementsByTagName("FAX").item(0).getFirstChild().getNodeValue();System.out.println("fax:" + content);content = element.getElementsByTagName("EMAIL").item(0).getFirstChild().getNodeValue();System.out.println("email:" + content);System.out.println("--------------------------------------");}}
}
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<a><PERSON><NAME id="cheng">海成</NAME><ADDRESS>立水桥</ADDRESS><TEL>15210221200</TEL><FAX>无</FAX><EMAIL>hai_cheng@sina.cn</EMAIL></PERSON><PERSON><NAME id="yang">海洋</NAME><ADDRESS>庆安县</ADDRESS><TEL>15210221200</TEL><FAX>无</FAX><EMAIL>hai_yang@sina.cn</EMAIL></PERSON><PERSON><NAME id="long">海龙</NAME><ADDRESS>庆安县</ADDRESS><TEL>15210221200</TEL><FAX>无</FAX><EMAIL>hai_long@sina.cn</EMAIL></PERSON>
</a>
package dom;import java.io.File;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;/*** 使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上* @author zhanglong**/
public class DomTest3
{public static void main(String[] args) throws Exception{DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document doc = db.parse(new File("candidate.xml"));//获得根元素结点Element root = doc.getDocumentElement();parseElement(root);}private static void parseElement(Element element){String tagName = element.getNodeName();//节点名称NodeList children = element.getChildNodes();System.out.print("<" + tagName);//element元素的所有属性所构成的NamedNodeMap对象,需要对其进行判断NamedNodeMap map = element.getAttributes();//如果该元素存在属性if(null != map){for(int i = 0; i < map.getLength(); i++){//获得该元素的每一个属性Attr attr = (Attr)map.item(i);String attrName = attr.getName();String attrValue = attr.getValue();System.out.print(" " + attrName + "=\"" + attrValue + "\"");}}System.out.print(">");for(int i = 0; i < children.getLength(); i++){Node node = children.item(i);//获得结点的类型short nodeType = node.getNodeType();if(nodeType == Node.ELEMENT_NODE){//是元素,继续递归parseElement((Element)node);}else if(nodeType == Node.TEXT_NODE){//递归出口System.out.print(node.getNodeValue());}else if(nodeType == Node.COMMENT_NODE){System.out.print("<!--");Comment comment = (Comment)node;//注释内容String data = comment.getData();System.out.print(data);System.out.print("-->");}}System.out.print("</" + tagName + ">");}
}
二、SAX(Simple APIs for XML)解析xml文件 XML简单应用程序接口。
与DOM不同,SAX提供的访问模式是一种顺序模式,而不是基于DOM的随机模式,这是一种快速读写XML文件的方式,当使用SAX分析器对xml文档进行解析的时候会触发一系列的事件,并激活相应的事件处理函数,应用程序通过这些事件处理函数对xml文档进行访问,因而SAX接口也被称为事件驱动接口。
实例三:
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<root><student id="1" group="1"><name>张三</name><sex>男</sex><age>18</age><email>zhangsan@163.com</email><birthday>1987-06-08</birthday><memo>好学生</memo></student><student id="2" group="2"><name>李四</name><sex>女</sex><age>18</age><email>lisi@163.com</email><birthday>1987-06-08</birthday><memo>好学生</memo></student><student id="3" group="3"><name>小王</name><sex>男</sex><age>18</age><email>xiaowang@163.com</email><birthday>1987-06-08</birthday><memo>好学生</memo></student><student id="4" group="4"><name>小张</name><sex>男</sex><age>18</age><email>xiaozhang@163.com</email><birthday>1987-06-08</birthday><memo>好学生</memo></student><student id="5" group="5"><name>小明</name><sex>男</sex><age>18</age><email>xiaoming@163.com</email><birthday>1987-06-08</birthday><memo>好学生</memo></student>
</root>
xml对应的JavaBean:
package sax;public class Student {private int id;private int group;private String name;private String sex;private int age;private String email;private String memo;private String birthday;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getGroup() {return group;}public void setGroup(int group) {this.group = group;}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 getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getMemo() {return memo;}public void setMemo(String memo) {this.memo = memo;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}}
解析类:
package sax;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;/*** 功能描述:采用sax方式解析XML<br>* * @author HaiCheng**/
public class SaxParseXml extends DefaultHandler{//存放遍历集合private List<Student> list;//构建Student对象private Student student;//用来存放每次遍历后的元素名称(节点名称)private String tagName;public List<Student> getList() {return list;}public void setList(List<Student> list) {this.list = list;}public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}public String getTagName() {return tagName;}public void setTagName(String tagName) {this.tagName = tagName;}//只调用一次 初始化list集合 @Overridepublic void startDocument() throws SAXException {list=new ArrayList<Student>();}//调用多次 开始解析@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {if(qName.equals("student")){student=new Student();//获取student节点上的id属性值student.setId(Integer.parseInt(attributes.getValue(0)));//获取student节点上的group属性值student.setGroup(Integer.parseInt(attributes.getValue(1)));}this.tagName=qName;}//调用多次 @Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {if(qName.equals("student")){this.list.add(this.student);}this.tagName=null;}//只调用一次@Overridepublic void endDocument() throws SAXException {}//调用多次@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {if(this.tagName!=null){String date=new String(ch,start,length);if(this.tagName.equals("name")){this.student.setName(date);}else if(this.tagName.equals("sex")){this.student.setSex(date);}else if(this.tagName.equals("age")){this.student.setAge(Integer.parseInt(date));}else if(this.tagName.equals("email")){this.student.setEmail(date);}else if(this.tagName.equals("birthday")){this.student.setBirthday(date);}else if(this.tagName.equals("memo")){this.student.setMemo(date);}}}public static void main(String[] args) {SAXParser parser = null;try {//构建SAXParserparser = SAXParserFactory.newInstance().newSAXParser();//实例化 DefaultHandler对象SaxParseXml parseXml=new SaxParseXml();
/** 加载资源文件 转化为一个输入流,搞不懂为什么下面注释掉的那行代码获取不到文件流,* 上网查了一些说大多数是路径的原因,可是怎么试验都获取到的都是null,所以只能用* InputStream stream=new FileInputStream("Student.xml") ;来获取文件流*///InputStream stream=SaxParseXml.class.getClassLoader().getResourceAsStream("Student.xml");InputStream stream=new FileInputStream("Student.xml") ;System.out.println(stream); //调用parse()方法parser.parse(stream, parseXml);//遍历结果List<Student> list=parseXml.getList();for(Student student:list){System.out.println("id:"+student.getId()+"\tgroup:"+student.getGroup()+"\tname:"+student.getName()+"\tsex:"+student.getSex()+"\tage:"+student.getAge()+"\temail:"+student.getEmail()+"\tbirthday:"+student.getBirthday()+"\tmemo:"+student.getMemo());}} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }
关于实例三的粗体注释部分相关的一些东西贴出来:
this.getClass().getClassLoader().getResource("template");
首先,调用对象的getClass()方法是获得对象当前的类类型,这部分数据存在方法区中,而后在类类型上调用getClassLoader()方法是得到当前类型的类加载器,我们知道在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就是保证是和类类型同一个加载器加载的。
最后调用了类加载器的getResourceAsStream()方法来加载资源。
===
JAVA运行时,首先会在指定的类路径下(classpath路径下)搜索JAVA编译后的字节码文件(class文件),然后通过类加载器加载到虚拟机中。 DBConn.class.getClassLoader().getResourceAsStream("database.properties") 1、DBConn.class得到表示DBConn类的Class对象,请参照JDK中对Class的说明 http://wenku.baidu.com/view/1fa5e8ebe009581b6bd9ebe1.html。 2、通过Class的getClassLoader方法取得加载DBConn类的类加载器对象ClassLoader。 3、调用ClassLoader的getResourceAsStream方法从类加载路径取得文件的输入流(会通过当前的ClassLoader的findResource方法查找指定文件),请参照: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29。

老兄和我犯的错误是一样的:
要区分Class的getResourceAsStream和ClassLoader的getResourceAsStream方法。
ClassLoader的该方法如果name以/开头那么就什么也找不到了。而Class的getResourceAsStream方法如果name以/开头那么就把/以后的name传递给ClassLoader的
getResourceAsStream方法。如果不已/开头那么将该class的包名加上name作为参数(用/代替.)之后
传给ClassLoader的对应方法。看一下程序:
package com.test;
import java.io.*;public class UseResourceTest {
public static void main(String[] args) throws Exception {
UseResourceTest test = new UseResourceTest();
InputStream in = test.getClass().getResourceAsStream("a.txt");
System.out.println(in);
}
}
效果相当于:
package com.test;
import java.io.*;public class UseResourceTest {
public static void main(String[] args) throws Exception {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("com/test/a.txt");
System.out.println(in);
}
}
所以说我上面的那个例子可以有三种方式获取到io流:
InputStream stream=SaxParseXml.class.getClassLoader().getResourceAsStream("sax/Student.xml");
InputStream stream=SaxParseXml.class.getResourceAsStream("Student.xml");
InputStream stream=new FileInputStream("Student.xml") ;
/*标记一下以后继续补充这部分相关的知识
*/

三、JDOM解析XML
JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析、生成、序列化以及多种操作。(http://jdom.org)
•JDOM 直接为JAVA编程服务。它利用更为强有力的JAVA语言的诸多特性(方法重载、集合概念等),把SAX和DOM的功能有效地结合起来。
•JDOM是用Java语言读、写、操作XML的新API函数。在直接、简单和高效的前提下,这些API函数被最大限度的优化。
实例四:
JDOM创建XML文件:
package jdom;
import java.io.FileWriter;import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;public class JDomTest1
{public static void main(String[] args) throws Exception{Document document = new Document();Element root = new Element("root");document.addContent(root);Comment comment = new Comment("This is my comments");root.addContent(comment);Element e = new Element("hello");e.setAttribute("sohu", "www.sohu.com");root.addContent(e);Element e2 = new Element("world");Attribute attr = new Attribute("test", "hehe");e2.setAttribute(attr);e.addContent(e2);e2.addContent(new Element("aaa").setAttribute("a", "b").setAttribute("x", "y").setAttribute("gg", "hh").setText("text content"));Format format = Format.getPrettyFormat();format.setIndent(" ");
// format.setEncoding("gbk");XMLOutputter out = new XMLOutputter(format);out.output(document, new FileWriter("jdom.xml"));}
}
实例五:
JDOM解析XML文件
package jdom;import java.io.File;
import java.io.FileOutputStream;
import java.util.List;import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;public class JDomTest2
{public static void main(String[] args) throws Exception{SAXBuilder builder = new SAXBuilder();Document doc = builder.build(new File("jdom.xml"));Element element = doc.getRootElement();System.out.println(element.getName());Element hello = element.getChild("hello");System.out.println(hello.getText());List list = hello.getAttributes();for(int i = 0 ;i < list.size(); i++){Attribute attr = (Attribute)list.get(i);String attrName = attr.getName();String attrValue = attr.getValue();System.out.println(attrName + "=" + attrValue);}hello.removeChild("world");XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent(" "));out.output(doc, new FileOutputStream("jdom2.xml")); }
}
四、Dom4j方式:
实例六:
package dom4j;import java.io.FileOutputStream;
import java.io.FileWriter;import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;public class Dom4jTest1
{public static void main(String[] args) throws Exception{// 创建文档并设置文档的根元素节点 :第一种方式// Document document = DocumentHelper.createDocument();//// Element root = DocumentHelper.createElement("student");//// document.setRootElement(root);// 创建文档并设置文档的根元素节点 :第二种方式Element root = DocumentHelper.createElement("student");Document document = DocumentHelper.createDocument(root);root.addAttribute("name", "zhangsan");Element helloElement = root.addElement("hello");Element worldElement = root.addElement("world");helloElement.setText("hello");worldElement.setText("world");helloElement.addAttribute("age", "20");XMLWriter xmlWriter = new XMLWriter();xmlWriter.write(document);OutputFormat format = new OutputFormat(" ", true);XMLWriter xmlWriter2 = new XMLWriter(new FileOutputStream("student2.xml"), format);xmlWriter2.write(document);XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("student3.xml"), format);xmlWriter3.write(document);xmlWriter3.close();}
}
实例七:
package dom4j;import java.io.File;
import java.util.Iterator;
import java.util.List;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;
import org.dom4j.io.SAXReader;public class Dom4jTest2
{public static void main(String[] args) throws Exception{SAXReader saxReader = new SAXReader();Document doc = saxReader.read(new File("student2.xml"));Element root = doc.getRootElement();System.out.println("root element: " + root.getName());List childList = root.elements();System.out.println(childList.size());List childList2 = root.elements("hello");System.out.println(childList2.size());Element first = root.element("hello");System.out.println(first.attributeValue("age"));for(Iterator iter = root.elementIterator(); iter.hasNext();){Element e = (Element)iter.next();System.out.println(e.attributeValue("age"));}System.out.println("---------------------------");DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();org.w3c.dom.Document document = db.parse(new File("student2.xml"));DOMReader domReader = new DOMReader();//将JAXP的Document转换为dom4j的DocumentDocument d = domReader.read(document);Element rootElement = d.getRootElement();System.out.println(rootElement.getName());}
}