解析xml文件的四种方式

来源:互联网 发布:免费数据库有哪些 编辑:程序博客网 时间:2024/05/22 01:32

xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童话</name>
<year>2004</year>
<price>77</price>
<language>English</language>
</book>

</bookstore>

第一种方式(dom4jxml):

package com.lcb.dom4jxml;


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.lcb.saxxnl.Book;


public class Dom4jParseXML {


public static void main(String[] args) {
SAXReader reader = new SAXReader();
ArrayList<Book> booksList = new ArrayList<Book>();
try {
Document document = reader.read(new File("books.xml"));
Element bookStore = document.getRootElement();
Iterator iter = bookStore.elementIterator();
while (iter.hasNext()) {
Book book = new Book();
Element bookElement = (Element) iter.next();
List<Attribute> attrs = bookElement.attributes();
for (Attribute attr : attrs) {
if(attr.getName().equals("id")){
book.setId(attr.getName());
}
System.out.print(attr.getName() + ":");
System.out.println(attr.getValue());
}
Iterator iter2 = bookElement.elementIterator();
while (iter2.hasNext()) {
Element nodes = (Element) iter2.next();
String nodeName = nodes.getName();
String nodeValue = nodes.getStringValue();
  if(nodeName.equals("name")){
book.setName(nodeValue);
}else if(nodeName.equals("author")){
book.setAuthor(nodeValue);
}else if(nodeName.equals("year")){
book.setYear(nodeValue);
}else if(nodeName.equals("price")){
book.setPrice(nodeValue);
}else if(nodeName.equals("language")){
book.setLanguage(nodeValue);
}
System.out.print(nodes.getName() + ":");
System.out.println(nodes.getStringValue());
}
booksList.add(book);
}
System.out.println(booksList.size());
System.out.println(booksList.get(0).getName()+" "+booksList.get(1).getName());
} catch (DocumentException e) {
e.printStackTrace();
}


}
}



第二种方式(domxml):

package com.lcb.domxml;


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


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class DOMParseXML {


public static void main(String[] args) {
DocumentBuilderFactory dmf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dmf.newDocumentBuilder();
try {
Document document = db.parse("books.xml");
NodeList bookList = document.getElementsByTagName("book");
//System.out.println(bookList.getLength());
// 遍历book的属性方式一
for (int i = 0; i < bookList.getLength(); i++) {
Node book = bookList.item(i);
// System.out.println(book.getNodeName());
// NamedNodeMap attrs = book.getAttributes();
// //System.out.println(attrs.getLength());
// for (int j = 0; j < attrs.getLength(); j++) {
// Node attr = attrs.item(j);
// System.out.println(attr);
// }
// 遍历book的属性方式二
Element element = (Element) bookList.item(i);
System.out.println(element.getAttribute("id"));
NodeList childNodes = book.getChildNodes();
//System.out.println(childNodes.getLength());
for (int i1 = 0; i1 < childNodes.getLength(); i1++) {
if (childNodes.item(i1).getNodeType() == Node.ELEMENT_NODE)
System.out.println(childNodes.item(i1).getFirstChild().getNodeValue());
}
System.out.println("------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}



第三种方式(jdomxml):

package com.lcb.jdomxml;


import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;


import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


import com.lcb.saxxnl.Book;


public class JDOMParseXML {


public static void main(String[] args) {
SAXBuilder saxBuilder = new SAXBuilder();
FileInputStream in;
List<Book> booksList = new ArrayList<Book>();
try {
in = new FileInputStream("books.xml");
Document document = saxBuilder.build(in);
Element rootElement = document.getRootElement();
List<Element> bookList = rootElement.getChildren();
for (Element book : bookList) {
Book bookEntity = new Book();
System.out.println("开始解析" + (bookList.indexOf(book) + 1) + "本书");
List<Attribute> attrs = book.getAttributes();
for (Attribute attr : attrs) {
if(attr.getName().equals("id")){
bookEntity.setId(attr.getValue());
}
System.out.print(attr.getName()+":");
System.out.println(attr.getValue());
}
List<Element> nodes = book.getChildren();
for(Element bookChild:nodes){
String nodeName = bookChild.getName();
String nodeValue = bookChild.getValue();
if(nodeName.equals("name")){
bookEntity.setName(nodeValue);
}else if(nodeName.equals("author")){
bookEntity.setAuthor(nodeValue);
}else if(nodeName.equals("year")){
bookEntity.setYear(nodeValue);
}else if(nodeName.equals("price")){
bookEntity.setPrice(nodeValue);
}else if(nodeName.equals("language")){
bookEntity.setLanguage(nodeValue);
}
System.out.print(bookChild.getName()+":");
System.out.println(bookChild.getValue());
}
System.out.println("结束解析" + (bookList.indexOf(book) + 1) + "本书");
booksList.add(bookEntity);
bookEntity = null;
}
System.out.println(booksList.size());
System.out.println(booksList.get(0).getName()+"  "+booksList.get(1).getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}



第四种方式(saxxnl):

package com.lcb.saxxnl;


public class Book {
private String id;
private String name;
private String author;
private String year;
private String price;
private String language;


public String getId() {
return id;
}


public void setId(String id) {
this.id = id;
}


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 String getPrice() {
return price;
}


public void setPrice(String price) {
this.price = price;
}


public String getLanguage() {
return language;
}


public void setLanguage(String language) {
this.language = language;
}


}

---------------------------------------------

package com.lcb.saxxnl;


import java.util.ArrayList;


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


public class SAXParserHandler extends DefaultHandler {
int bookIndex = 0;
String value = null;
Book book = null;
    ArrayList<Book> bookList = new ArrayList<Book>();


/**
* 开始解析xml元素
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (qName.equals("book")) {
book = new Book();
bookIndex++;
System.out.println("------第" + bookIndex + "本书解析开始------");
// System.out.println(attributes.getQName(0)+" "+attributes.getValue(0));
int num = attributes.getLength();
for (int i = 0; i < num; i++) {
System.out.println(attributes.getQName(i) + ":"
+ attributes.getValue(i));
if (attributes.getQName(i).equals("id")) {
book.setId(attributes.getValue(i));
}
}
} else if (qName.equals("bookstore")) {


} else {
System.out.print(qName + ":");
}
}


@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (qName.equals("book")) {
bookList.add(book);
book = null;
System.out.println("------第" + bookIndex + "本书解析结束------");
} 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 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解析结束");
}


@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
value = new String(ch, start, length).trim();
if (value != "" || value != null)
System.out.println(value);
}
}

---------------------------------------------

package com.lcb.saxxnl;


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


public class SAXParseXML {
public static void main(String[] args) {
SAXParserFactory apf = SAXParserFactory.newInstance();
try {
SAXParser sp = apf.newSAXParser();
SAXParserHandler sph = new SAXParserHandler();
sp.parse("books.xml", sph);
System.out.println("总共有 "+sph.bookList.size()+" 本书");
for(int i = 0;i<sph.bookList.size();i++){
System.out.println(sph.bookList.get(i).getId()+" "+sph.bookList.get(i).getName());
}

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

0 0
原创粉丝点击