这是自己整理的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 
胖胖泡泡 阅读(184) 
评论(0)  编辑  收藏