這是自己整理的xml解析,參考了網上的例子:
- <?xml version="1.0" encoding="UTF-8"?>
- <catalog>
-
- <books title="XML Zone" publisher="IBM developerWorks">
- <book level="Intermediate" date="December-2001">
- <title>Java OO Book</title>
- <author>author</author>
- </book>
- </books>
- </catalog>
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<!--An XML Catalog-->
<books title="XML Zone" publisher="IBM developerWorks">
<book level="Intermediate" date="December-2001">
<title>Java OO Book</title>
<author>author</author>
</book>
</books>
</catalog>
1、jdom解析
- package cn.xml;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
-
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.JDOMException;
- import org.jdom.input.SAXBuilder;
- import org.jdom.output.XMLOutputter;
-
-
-
-
-
-
- public class JDomParse {
-
-
-
-
-
-
-
- public static void main(String[] args) throws FileNotFoundException, IOException, JDOMException {
- String xmlpath="c:/catalog.xml";
-
- SAXBuilder builder=new SAXBuilder(false);
-
- Document doc=builder.build(xmlpath);
-
- Element root=doc.getRootElement();
-
- List bookslist=root.getChildren("books");
-
- for (Iterator iter = bookslist.iterator(); iter.hasNext();) {
- Element books= (Element) iter.next();
- List bookList=books.getChildren("book");
- for(Iterator it=bookList.iterator();it.hasNext();){
- Element book= (Element) it.next();
-
- String level=book.getAttributeValue("level");
- System.out.println(level);
-
- String author=book.getChildTextTrim("author");
- System.out.println(author);
-
- book.getChild("author").setText("author_test");
- }
-
- }
-
-
-
-
- }
-
- }
package cn.xml;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
/**
* yicha
* Dec 2, 2008 JDom解析
*/
public class JDomParse {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
* @throws JDOMException
*/
public static void main(String[] args) throws FileNotFoundException, IOException, JDOMException {
String xmlpath="c:/catalog.xml";
//使用JDOM首先要指定使用什么解析器
SAXBuilder builder=new SAXBuilder(false);//這表示使用的是默認的解析器
//得到Document,以后要進行的所有操作都是對這個Document操作的
Document doc=builder.build(xmlpath);
//得到根元素
Element root=doc.getRootElement();
//得到元素(節點)的集合
List bookslist=root.getChildren("books");
//輪循List集合
for (Iterator iter = bookslist.iterator(); iter.hasNext();) {
Element books= (Element) iter.next();
List bookList=books.getChildren("book");
for(Iterator it=bookList.iterator();it.hasNext();){
Element book= (Element) it.next();
//取得元素的屬性
String level=book.getAttributeValue("level");
System.out.println(level);
//取得元素的子元素(為最低層元素)的值 注意的是,必須確定book元素的名為“name”的子元素只有一個。
String author=book.getChildTextTrim("author");
System.out.println(author);
//改變元素(為最低層元素)的值;對Document的修改,并沒有在實際的XML文檔中進行修改
book.getChild("author").setText("author_test");
}
}
//保存Document的修改到XML文件中
// XMLOutputter outputter=new XMLOutputter();
// outputter.output(doc,new FileOutputStream(xmlpath));
}
}
dom解析:
- package cn.xml;
-
- import java.io.File;
-
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
-
- import org.w3c.dom.Document;
- import org.w3c.dom.NodeList;
-
-
-
-
-
-
-
- public class DomPhase {
-
-
-
-
- public static void main(String[] args) {
- long lasting =System.currentTimeMillis();
- try{
- File f=new File("c:/catalog.xml");
- DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
- DocumentBuilder builder=factory.newDocumentBuilder();
- Document doc = builder.parse(f);
- NodeList nl = doc.getElementsByTagName("author");
- for (int i=0;i<nl.getLength();i++){
- System.out.println("firstname:" + doc.getElementsByTagName("firstname").item(i).getFirstChild().getNodeValue());
- System.out.println(" lastname:" + doc.getElementsByTagName("lastname").item(i).getFirstChild().getNodeValue());
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- System.out.println("運行時間:"+(System.currentTimeMillis() - lasting)+" 毫秒");
- }
- }
package cn.xml;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
/**
* yicha
* Dec 1, 2008
* DOM解析
*/
public class DomPhase {
/**
* @param args
*/
public static void main(String[] args) {
long lasting =System.currentTimeMillis();
try{
File f=new File("c:/catalog.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("author");
for (int i=0;i<nl.getLength();i++){
System.out.println("firstname:" + doc.getElementsByTagName("firstname").item(i).getFirstChild().getNodeValue());
System.out.println(" lastname:" + doc.getElementsByTagName("lastname").item(i).getFirstChild().getNodeValue());
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("運行時間:"+(System.currentTimeMillis() - lasting)+" 毫秒");
}
}
dom4j解析:
package cn.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* yicha
* Dec 1, 2008
*/
public class Dom4JPhase {
/**
* 產生xml文檔
*/
public void generateDocument(){
//使用 DocumentHelper 類創建一個文檔實例。 DocumentHelper 是生成 XML 文檔節點的 dom4j API 工廠類
Document document = DocumentHelper.createDocument();
//使用 addElement()方法創建根元素catalog , addElement()用于向 XML 文檔中增加元素
Element catalogElement = document.addElement("catalog");
//在 catalog 元素中使用 addComment() 方法添加注釋"An XML catalog"
catalogElement.addComment("An XML Catalog");
//在 catalog 元素中使用 addProcessingInstruction() 方法增加一個處理指令 (不知有什么用)
// catalogElement.addProcessingInstruction("target","text");
//在 catalog 元素中使用 addElement() 方法增加 journal 節點
Element booksElement = catalogElement.addElement("books");
//使用 addAttribute() 方法向 book節點添加 title 和 publisher 屬性
booksElement.addAttribute("title", "XML Zone");
booksElement.addAttribute("publisher", "IBM developerWorks");
//添加子節點
Element bookElement=booksElement.addElement("book");
//添加屬性
bookElement.addAttribute("level", "Intermediate");
bookElement.addAttribute("date", "December-2001");
//添加節點
Element titleElement=bookElement.addElement("title");
//添加內容
titleElement.setText("Java OO Book");
//添加節點
Element authorElement=bookElement.addElement("author");
//添加節點
authorElement.setText("author");
//可以使用 addDocType() 方法添加文檔類型說明
//這樣就向 XML 文檔中增加文檔類型說明:
// document.addDocType("catalog","nikee","file://c:/Dtds/catalog.dtd");
try{
FileOutputStream fos=new FileOutputStream("c:/catalog.xml");
OutputFormat of=new OutputFormat(" ", true);
XMLWriter xw=new XMLWriter(fos, of);
xw.write( document );
xw.close();
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
/**
* 讀取xml文件的元素值
* @param list
*/
public void getXMLValue(List list){
// List list=element.elements();
if(list==null||list.size()==0){
return;
}
for(int i=0;i<list.size();i++){
Element foo = (Element) list.get(i);
System.out.println(foo.getName()+"="+foo.getData().toString().trim());
List result=foo.elements();
if(result!=null||result.size()>0){
this.getXMLValue(result);//遞歸
}
}
}
/**
* 根據節點名獲取值
* @param fileName
* @param name
*/
public void getElement(String fileName,String name){
Document document = this.readXML(fileName);
Element root=this.getRootElement(document);
// 枚舉名稱為name的節點
for ( Iterator i = root.elementIterator(name); i.hasNext();) {
Element foo = (Element) i.next();
System.out.println(foo.getName()+"="+foo.getData());
}
// 枚舉所有子節點
// for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
// Element foo = (Element) i.next();
// System.out.println(foo.getName()+"="+foo.getData());
// }
}
/**
* 根據節點名獲取值
* @param fileName
* @param name
*/
public void getAttribute(Element element,String name){
// 枚舉屬性
for ( Iterator i = element.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
System.out.println(attribute.getName()+"="+attribute.getData());
}
}
/**
* 得到root節點
* @param doc
* @return
*/
public Element getRootElement(Document doc){
return doc.getRootElement();
}
/**
* 讀取xml文件
* @param fileName
* @return 返回document對象
*/
public Document readXML(String fileName){
SAXReader saxReader = new SAXReader();
Document document=null;
try {
document = saxReader.read(new File(fileName));
}catch(Exception e){
System.out.println("readXML has error:"+e.getMessage());
e.printStackTrace();
}
return document;
}
/**
* 遍歷整個XML文件,獲取所有節點的值與其屬性的值,并放入HashMap中
* @param 待遍歷的XML文件
*/
public void iterateWholeXML(String filename){
Document document = this.readXML(filename);
Element root=this.getRootElement(document);
List list=root.elements();
this.getXMLValue(list);
}
public static void main(String[] argv){
Dom4JPhase dom4j=new Dom4JPhase();
dom4j.generateDocument();
String fileName="c:/catalog.xml";
String elementName="book";
// dom4j.generateDocument();
long lasting = System.currentTimeMillis();
dom4j.iterateWholeXML(fileName);
// dom4j.getElement(fileName, elementName);
System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + " 毫秒");
}
}
rax解析:
- package cn.xml;
-
-
-
-
-
-
- import java.net.URL;
- import java.util.Properties;
-
- import org.xml.sax.*;
- import org.xml.sax.helpers.*;
- import javax.xml.parsers.*;
-
-
-
-
-
-
-
- public class SAXReader extends DefaultHandler {
-
-
-
-
-
- private Properties props;
- private String currentName;
- private StringBuffer currentValue = new StringBuffer();
-
-
- public SAXReader() {
- this.props=new Properties();
- }
-
-
- public Properties getPrpos() {
- return this.props;
- }
-
-
- public String getCurrentName(){
- return currentName;
- }
-
-
-
-
-
-
- public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{
- currentValue.delete(0,currentValue.length());
- this.currentName=qName;
- }
-
-
-
-
-
-
- public void characters(char[] ch,int start,int length)
- throws SAXException
- {
- currentValue.append(ch,start,length);
- }
-
-
-
-
- public void endElement(String uri, String localName, String qName) throws SAXException {
- props.put(qName.toLowerCase(), currentValue.toString().trim());
- }
-
-
-
- public static void main(String args[]) {
- long lasting = System.currentTimeMillis();
- String fileName="c:/catalog.xml";
- SAXParserFactory sf = SAXParserFactory.newInstance();
- SAXParser sp;
- try {
- sp = sf.newSAXParser();
- SAXReader reader = new SAXReader();
- sp.parse(new InputSource(fileName), reader);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + "毫秒");
- }
-
- }
package cn.xml;
/**
* yicha
* Jul 3, 2008
*/
import java.net.URL;
import java.util.Properties;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
/**
* SAX 解析
* @author yicha
*
*/
public class SAXReader extends DefaultHandler {
/*props:用于存放解析器解析出來的的節點和節點對應的屬性,為哈希表
* currentName:當前節點的名稱
* currentValue:用于存放當前節點所對應的屬性值
*/
private Properties props;
private String currentName;
private StringBuffer currentValue = new StringBuffer();
public SAXReader() {
this.props=new Properties();
}
public Properties getPrpos() {
return this.props;
}
public String getCurrentName(){
return currentName;
}
/*
* 讀取<xxx>中的值xxx并將其付給qname,通知解析器解析當前節點對應的值。同時對currentValue緩沖器清空,用來保存當前qname對應屬性值。
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{
currentValue.delete(0,currentValue.length());
this.currentName=qName;
}
/*讀取<xxx></xxx>之間的屬性值,并將其首先以字符形式保存至字符數組ch中,并記錄對應長度,以確保以
* length為長度的字符為一個整體,然后講字符數組中的內容按照length長度為整體加到currentValue緩沖器中
* 每次讀取xml文件后只會在ch中保存當前所解析到的值,currentValue中也只會有當前的節點所對應的唯一值
*/
public void characters(char[] ch,int start,int length)
throws SAXException
{
currentValue.append(ch,start,length);
}
/* 當遇到</xxx>時,將當前的qname,和qname所對應的位于currentValue緩沖器中的值保存到props這個哈希表中去,供外部程序調用
* @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}
public static void main(String args[]) {
long lasting = System.currentTimeMillis();
String fileName="c:/catalog.xml";
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp;
try {
sp = sf.newSAXParser();
SAXReader reader = new SAXReader();
sp.parse(new InputSource(fileName), reader);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + "毫秒");
}
}
- package cn.xml;
-
- import java.net.URL;
- import java.util.Iterator;
- import java.util.Properties;
-
- import javax.xml.parsers.SAXParser;
- import javax.xml.parsers.SAXParserFactory;
-
-
-
-
-
-
- public class SaxPhase {
- private Properties props;
- public SaxPhase(){
- props=new Properties();
- }
-
- public Properties getProps(){
- return this.props;
- }
- public void parse(String filename) throws Exception {
-
- SAXReader handler = new SAXReader();
-
- SAXParserFactory factory = SAXParserFactory.newInstance();
-
- SAXParser parser = factory.newSAXParser();
-
- URL confURL = SAXReader.class.getClassLoader().getResource(filename);
- try{
- parser.parse(confURL.toString(), handler);
- props = handler.getPrpos();
- }finally {
-
- factory=null;
- parser=null;
- handler=null;
- }
-
- }
-
-
-
- public String getElementValue(String elementName) {
-
- String elementValue=null;
- elementValue=props.getProperty(elementName);
- return elementValue;
- }
-
-
-
- public static void main(String[] args) {
- SaxPhase sp=new SaxPhase();
- String filename="testXML.xml";
- try {
- sp.parse(filename);
- Properties props=sp.getProps();
-
- Iterator it=props.keySet().iterator();
- while(it.hasNext()){
- String key=it.next().toString();
- System.out.println(props.get(key)+"");
- }
-
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- }
轉自:http://canofy.javaeye.com/blog/285107
posted on 2009-06-22 18:18
胖胖泡泡 閱讀(179)
評論(0) 編輯 收藏