java中解析xml文件的五种常见方法:DOM4J,dom,pull,SAX,Jdom

package com.zhidi.dom4jtest;


import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import com.imooc.entity.Book;


public class DOM4JTest {
private static ArrayList<Book> bookList = new ArrayList<Book>();
/**
* @param args
*/
public static void main(String[] args) {
// 解析books.xml文件
// 创建SAXReader的对象reader
SAXReader reader = new SAXReader();
try {
// 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
Document document = reader.read(new File("src/res/books.xml"));
// 通过document对象获取根节点bookstore
Element bookStore = document.getRootElement();
// 通过element对象的elementIterator方法获取迭代器
Iterator it = bookStore.elementIterator();
// 遍历迭代器,获取根节点中的信息(书籍)
while (it.hasNext()) {
System.out.println("=====开始遍历某一本书=====");
Element book = (Element) it.next();
// 获取book的属性名以及 属性值
List<Attribute> bookAttrs = book.attributes();
for (Attribute attr : bookAttrs) {
System.out.println("属性名:" + attr.getName() + "--属性值:"
+ attr.getValue());
}
Iterator itt = book.elementIterator();
while (itt.hasNext()) {
Element bookChild = (Element) itt.next();
System.out.println("节点名:" + bookChild.getName() + "--节点值:" + bookChild.getStringValue());
}
System.out.println("=====结束遍历某一本书=====");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}

以上DOM4J方法解析Xml文件,其解析过程就是将其内容解析出来,供程序员阅读,xml文件的内容多是配置信息。

DOM4J需要引入加油包,用多种方法读取其中的内容。


package com.zhidi.test;


import java.io.IOException;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/*DOM解析,是Java自有的,从体验上看,较为陌生,需要实例化多种类,代码量相对适中
 * 
 */
public class BookeDemo {


public static void main(String[] args) {
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder的对象
try {
DocumentBuilder db=dbf.newDocumentBuilder();
Document document=db.parse("books.xml");

NodeList list=document.getElementsByTagName("book");
System.out.println(list.getLength());
for (int i = 0; i <list.getLength() ; i++) {
Node node=list.item(i);

NamedNodeMap nnm=node.getAttributes();
System.out.println("属性的个数"+nnm.getLength());
for (int j = 0; j < nnm.getLength(); j++) {
Node nd =nnm.item(j);
System.out.println("属性名:"+nd.getNodeName());
System.out.println("属性值:"+nd.getNodeValue());
}
NodeList nl=node.getChildNodes();

for (int k= 0; k < nl.getLength(); k++) {
if(nl.item(k).getNodeType()==Node.ELEMENT_NODE){
//此处判断不清楚原因
System.out.println(nl.item(k).getNodeName());
System.out.println(nl.item(k).getFirstChild().getNodeValue());
}

}
}

} catch (ParserConfigurationException | SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//创建DocumentBuilder对象

//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下

//获取所有book节点的集合

//通过nodelist的getLength()方法可以获取bookList的长度


//遍历每一个book节点

//通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始

// 获取book节点的所有属性集合
//遍历book的属性

//通过item(index)方法获取book节点的某一个属性

//获取属性名

//获取属性值

}
// //前提:已经知道book节点有且只能有1个id属性
// //将book节点进行强制类型转换,转换成Element类型
//
// //通过getAttribute("id")方法获取属性值
//
//解析book节点的子节点

//遍历childNodes获取每个节点的节点名和节点值



//区分出text类型的node以及element类型的node

//获取了element类型节点的节点名


// 获取了element类型节点的节点值

}
以上Dom方法解析方法,不需要加油包,需要需要java自带的方法,


package com.pullxml;


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


import static org.xmlpull.v1.XmlPullParser.*;


import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;


/**
 * //1.创建解析器工厂类对象
 * @author Administrator
 *2.创建解析器对象;
 *3.位解析器指定待解析的资源
 *4.开始解析

*解析xml是基于事件的
* 1.文档开始:START_DOCUMENT
* 2.标记开始:START_TAG
* 3.标记结束:END_TAG
* 4.文档结束:END_DOCUMENT
*/
 /*此程序用pull方法解析XML文件,优点是多用switch方法,陌生的方法较少,容易理解;能够对特定的标记名和标记值进行操作。
  * 缺点是程序量较大,效率较低。
  * 此方法适合于对于XML文档进行修改,对特定标识进行查询的情况下。
  * 也需要导入加油包
  */
public class PullXmlDemo {


public static void main(String[] args) throws XmlPullParserException, IOException {

XmlPullParserFactory xpf= XmlPullParserFactory.newInstance();

XmlPullParser xpp=xpf.newPullParser();

xpp.setInput(new FileReader("books.xml"));

int event=xpp.getEventType();

while(event!=END_DOCUMENT){
switch(event){
case START_DOCUMENT:
System.out.println("文件开始解析");
break;
case START_TAG:
String s1=xpp.getName();
System.out.println("标记开始"+s1);

switch(s1){
case "id":
String s2=xpp.nextText();
System.out.println("id="+s2);
break;
case "name":
String name=xpp.nextText();
System.out.println("书名:"+name);
break;
case "author":
String author=xpp.nextText();
System.out.println("作者"+author);
break;
case "year":
String year=xpp.nextText();
System.out.println("出版年份:"+year);
break;
case "price":
String price=xpp.nextText();
System.out.println("价格:"+price);
break;
case "language":
String language=xpp.nextText();
System.out.println("语言:"+language);
break;
case "book":
int count=xpp.getAttributeCount();
if(count>0){

for (int i = 0; i < count; i++) {
String st1=xpp.getAttributeName(i);
String st2=xpp.getAttributeValue(i);
switch(st1){
case "id":
System.out.println("id="+st2);
break;
case "name":
System.out.println("书名:"+st2);
break;
case "author":
System.out.println("作者"+st2);
break;
case "year":
System.out.println("出版年份:"+st2);
break;
case "price":
System.out.println("价格:"+st2);
break;
case "language":
System.out.println("语言:"+st2);
break;
}
}
}
break;
}
case END_TAG:
String st=xpp.getName();
System.out.println("标记结束"+st);
break;


}

event=xpp.next();
}


}


}
以上pull解析xml文件的范例,其优点已写到程序中


package com.zhidi.jdomtest;


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


import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;


import com.imooc.entity.Book;




public class JDOMTest {
private static ArrayList<Book> booksList = new ArrayList<Book>();
/**
* @param args
*/
public static void main(String[] args) {
// 进行对books.xml文件的JDOM解析
// 准备工作
// 1.创建一个SAXBuilder的对象
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in;
try {
// 2.创建一个输入流,将xml文件加载到输入流中
in = new FileInputStream("src/res/books.xml");
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
// 3.通过saxBuilder的build方法,将输入流加载到saxBuilder中
Document document = saxBuilder.build(isr);
// 4.通过document对象获取xml文件的根节点
Element rootElement = document.getRootElement();
// 5.获取根节点下的子节点的List集合
List<Element> bookList = rootElement.getChildren();
// 继续进行解析
for (Element book : bookList) {
Book bookEntity = new Book();
System.out.println("======开始解析第" + (bookList.indexOf(book) + 1)
+ "书======");
// 解析book的属性集合
List<Attribute> attrList = book.getAttributes();
// //知道节点下属性名称时,获取节点值
// book.getAttributeValue("id");
// 遍历attrList(针对不清楚book节点下属性的名字及数量)
for (Attribute attr : attrList) {
// 获取属性名
String attrName = attr.getName();
// 获取属性值
String attrValue = attr.getValue();
System.out.println("属性名:" + attrName + "----属性值:"
+ attrValue);
if (attrName.equals("id")) {
bookEntity.setId(attrValue);
}
}
// 对book节点的子节点的节点名以及节点值的遍历
List<Element> bookChilds = book.getChildren();
for (Element child : bookChilds) {
System.out.println("节点名:" + child.getName() + "----节点值:"
+ child.getValue());
if (child.getName().equals("name")) {
bookEntity.setName(child.getValue());
}
else if (child.getName().equals("author")) {
bookEntity.setAuthor(child.getValue());
}
else if (child.getName().equals("year")) {
bookEntity.setYear(child.getValue());
}
else if (child.getName().equals("price")) {
bookEntity.setPrice(child.getValue());
}
else if (child.getName().equals("language")) {
bookEntity.setLanguage(child.getValue());
}
}
System.out.println("======结束解析第" + (bookList.indexOf(book) + 1)
+ "书======");
booksList.add(bookEntity);
bookEntity = null;
System.out.println(booksList.size());
System.out.println(booksList.get(0).getId());
System.out.println(booksList.get(0).getName());

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


}
以上是Jdom解析xml文件的范例,优点是用已学过集合等知识来解析文件,连续性好,容易理解。


package com.zhidi.handler;


import java.util.ArrayList;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import com.imooc.entity.Book;




public class SAXParserHandler extends DefaultHandler {
String value = null;
Book book = null;
private ArrayList<Book> bookList = new ArrayList<Book>();
public ArrayList<Book> getBookList() {
return bookList;
}


int bookIndex = 0;
/**
* 用来标识解析开始
*/
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
System.out.println("SAX解析开始");
}

/**
* 用来标识解析结束
*/
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
System.out.println("SAX解析结束");
}

/**
* 解析xml元素
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//调用DefaultHandler类的startElement方法
super.startElement(uri, localName, qName, attributes);
if (qName.equals("book")) {
bookIndex++;
//创建一个book对象
book = new Book();
//开始解析book元素的属性
System.out.println("======================开始遍历某一本书的内容=================");
// //已知book元素下属性的名称,根据属性名称获取属性值
// String value = attributes.getValue("id");
// System.out.println("book的属性值是:" + value);
//不知道book元素下属性的名称以及个数,如何获取属性名以及属性值
int num = attributes.getLength();
for(int i = 0; i < num; i++){
System.out.print("book元素的第" + (i + 1) +  "个属性名是:"
+ attributes.getQName(i));
System.out.println("---属性值是:" + attributes.getValue(i));
if (attributes.getQName(i).equals("id")) {
book.setId(attributes.getValue(i));
}
}
}
else if (!qName.equals("name") && !qName.equals("bookstore")) {
System.out.print("节点名是:" + qName + "---");
}
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//调用DefaultHandler类的endElement方法
super.endElement(uri, localName, qName);
//判断是否针对一本书已经遍历结束
if (qName.equals("book")) {
bookList.add(book);
book = null;
System.out.println("======================结束遍历某一本书的内容=================");
}
else if (qName.equals("name")) {
book.setName(value);
}
else if (qName.equals("author")) {
book.setAuthor(value);
}
else if (qName.equals("year")) {
book.setYear(value);
}
else if (qName.equals("price")) {
book.setPrice(value);
}
else if (qName.equals("language")) {
book.setLanguage(value);
}
}


@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
value = new String(ch, start, length);
if (!value.trim().equals("")) {
System.out.println("节点值是:" + value);
}
}
}
以上是SAX方法解析xml文件,其中方法承接以前学到的知识,具有连续性。容易理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值