DOM4J解析xml

一、DOM4J解析xml步骤

 

 

 

1、读取并解析XML文档,创建document对象

第一种方式可以从xml文件中读取内容,创建document对象

    SAXReader reader = new SAXReader(); Document document = reader.read(new File(fileName));

 

第二种方式直接根据xml字符串(比如通过webservice调用后台接口返回的应答字符串)创建document对象

 

    docuemnt=DocumentHelper.parseText(str);

2、取得Root节点   

    读取后的第二步,就是得到Root节点。熟悉XML的人都知道,一切XML分析都是从Root元素开始的。

    Element root=doc.getRootElement();

3、遍历XML树

    一般可以由根节点构造迭代器,通过迭代器来访问其元素

for ( Iterator i = root.elementIterator(); i.hasNext(); ) {   Element element = (Element) i.next(); System.out.println(element.getText()); }

二、代码演示

首先要将dom4j的jar包导入工程的lib下

1、xml文档

<?xml version="1.0" encoding="utf-8" ?> <books> <book id="1"> <name>A</name> <number>10</number> </book> <book id="2"> <name>B</name> <number>20</number> </book> <book id="3"> <name>C</name> <number>30</number> </book> <book id="4"> <name>D</name> <number>40</number> </book> </books>

2、java代码

 MyDom4j.java

import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class MyDom4j { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //创建document对象 Document d=createDC(); //将生成的xml文档的内容用输出流写入文件a.xml中 try { FileWriter fw=new FileWriter(new File("src/a.xml")); fw.write(d.asXML()); fw.flush(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //根据从a.xml文件的内容生成document对象,DocumentHelper.parseText这个方法会抛出DucumentException异常 Document docuemnt=null; try { SAXReader sax=new SAXReader(); docuemnt=sax.read(new File("src/a.xml")); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } //得到books下子节点的迭代器 Iterator it1=docuemnt.getRootElement().elementIterator(); int i=0,j=0; CRSet cr=null; while(it1.hasNext()){ Element child=(Element)it1.next(); //得到book下子节点的迭代器 Iterator it2=child.elementIterator(); if(i==0&&child.elements()!=null){ cr=new CRSet(child.elements().size()); } cr.AddRow(); while(it2.hasNext()){ Element e=(Element)it2.next(); String name=e.getName(); String value=e.getText(); cr.SetValue(i, j++, value); } i++; j=0; } //输出CRSet中的内容 print(cr); } //创建DOM4J documet对象 public static Document createDC(){ Document d=DocumentHelper.createDocument(); Element books=d.addElement("books"); Element book1= books.addElement("book"); book1.addAttribute("id", "1"); Element name1=book1.addElement("name"); name1.addText("A"); Element number1=book1.addElement("number"); number1.addText("10"); Element book2= books.addElement("book"); book2.addAttribute("id", "2"); Element name2=book2.addElement("name"); name2.addText("B"); Element number2=book2.addElement("number"); number2.addText("20"); Element book3= books.addElement("book"); book3.addAttribute("id", "3"); Element name3=book3.addElement("name"); name3.addText("C"); Element number3=book3.addElement("number"); number3.addText("30"); Element book4= books.addElement("book"); book4.addAttribute("id", "4"); Element name4=book4.addElement("name"); name4.addText("D"); Element number4=book4.addElement("number"); number4.addText("40"); d.setXMLEncoding("utf-8"); return d; } //打印CRSet对象中的数据 public static void print(CRSet cr) throws Exception{ if(cr!=null&&cr.getData().size()>0){ for(int i=0;i<cr.GetRowCount();i++) for(int j=0;j<cr.GetColumnCount();j++){ System.out.println("CRSet["+i+","+j+"]="+cr.GetValue(i, j)); } } } }

CRSet.java(这个类比较有用,用来存放从xml解析之后的内容)

import java.util.Iterator; import java.util.Vector; public class CRSet{ private int m_Cols= 1; private int m_Rows= 0; private Vector m_Data = new Vector(); public int GetColumnCount(){ return m_Cols; } public int GetRowCount(){ return m_Rows; } public CRSet(){} public CRSet(int cols) throws Exception{ if(cols <= 0 || cols>=1024) { throw new Exception("SRVC009T:Illegal range of column or row."+cols); } m_Cols = cols; m_Rows = 0; } public int AddRow() { for(int i=0; i<m_Cols; i++) { m_Data.add(""); } return m_Rows++; } public void SetValue(int row, int col, String value) throws Exception { if(row >= m_Rows || col >= m_Cols) { throw new Exception("SRVC009T:Illegal range of column or row." + row + "," + col); } m_Data.set(row*m_Cols+col,value); } public String GetValue(int row, int col) throws Exception { if(row >= m_Rows || col >= m_Cols) { throw new Exception("SRVC009T:Illegal range of column or row." + row + "," + col); } return (String)m_Data.elementAt(row*m_Cols+col); } public Vector getData(){ return m_Data; } public Iterator iterator() { return m_Data.iterator(); } }

3、MyDom4j .java运行之后的结果

CRSet[0,0]=A CRSet[0,1]=10 CRSet[1,0]=B CRSet[1,1]=20 CRSet[2,0]=C CRSet[2,1]=30 CRSet[3,0]=D CRSet[3,1]=40

希望今天写的对大家有所帮助,第一次发表博客,错误在所难免,哪位大虾如果发现了错误请指出来,共同进步,谢谢!

你可能感兴趣的:(DOM4J解析xml)