Java解析XML文檔——dom解析xml

Java解析XML文檔——dom解析xml
  
  1、前言
  
    用Java解析XML文檔,最經常使用的有兩種方法:使用基於事件的XML簡單API(Simple API for XML)稱爲SAX和基於樹和節點的文檔對象模型(Document Object Module)稱爲DOM。Sun公司提供了Java API for XML Parsing(JAXP)接口來使用SAX和DOM,經過JAXP,咱們可使用任何與JAXP兼容的XML解析器。
  
    JAXP接口包含了三個包:
  
    (1)org.w3c.dom
  
    W3C推薦的用於XML標準規劃文檔對象模型的接口。
  
    (2)org.xml.sax
  
    用於對XML進行語法分析的事件驅動的XML簡單API(SAX)
  
    (3)javax.xml.parsers解析器工廠工具,程序員得到並配置特殊的特殊語法分析器。
  
    2、前提
  
    DOM編程不要其它的依賴包,由於JDK裏自帶的JDK裏含有的上面提到的org.w3c.dom、org.xml.sax 和javax.xml.parsers包就能夠滿意條件了。
  
    3、使用DOM解析XML文檔
  
    咱們如今來看看DOM是如何解析XML的吧!一樣的,我將從一個簡單的不能再簡單的例子來講明DOM是如何解析XML文檔的,先讓咱們看看XML是什麼內容吧:
  
    《?xml version="1.0" encoding="gb2312"?>
  
    《books>
  
    《book email="zhoujunhui">
  
    《name>rjzjh《/name>
  
    《price>jjjjjj《/price>
  
    《/book>
  
    《/books>
  
    簡單的不能再簡單了。可是該有的都有了,根元素、屬性、子節點。好了,能反應問題就好了,下面來看看解析這個XML文件的Java代碼吧!
  
    1 public class DomParse {
  
    2
  
    public DomParse(){
  
    3
  
    DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
  
    4
  
    try {
  
    5
  
    DocumentBuilder dombuilder=domfac.newDocumentBuilder();
  
    6
  
    InputStream is=new FileInputStream("bin/library.xml");
  
    7
  
    Document doc=dombuilder.parse(is);
  
    8
  
    9
  
    Element root=doc.getDocumentElement();
  
    10
  
    NodeList books=root.getChildNodes();
  
    11
  
    if(books!=null){
  
    12
  
    for(int i=0;i<books.getlength();i++){
  
    13
  
    Node book=books.item(i);
  
    14
  
    if(book.getNodeType()==Node.ELEMENT_NODE){
  
    15
  
    String email=book.getAttributes().getNamedItem("email").getNodeValue();
  
    16
  
    System.out.println(email);
  
    17
  
    for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling()){
  
    18
  
    if(node.getNodeType()==Node.ELEMENT_NODE){
  
    19
  
    if(node.getNodeName().equals("name")){
  
    20
  
    String name=node.getNodeValue();
  
    21
  
    String name1=node.getFirstChild().getNodeValue();
  
    22
  
    System.out.println(name);
  
    23
  
    System.out.println(name1);
  
    24
  
    }
  
    25
  
    if(node.getNodeName().equals("price")){
  
    26
  
    String price=node.getFirstChild().getNodeValue();
  
    27
  
    System.out.println(price);
  
    28
  
    }
  
    29
  
    }
  
    30
  
    }
  
    31
  
    }
  
    32
  
    }
  
    33
  
    }
  
    34
  
    } catch (ParserConfigurationException e) {
  
    35
  
    e.printStackTrace();
  
    36
  
    } catch (FileNotFoundException e) {
  
    37
  
    e.printStackTrace();
  
    38
  
    } catch (SAXException e) {
  
    39
  
    e.printStackTrace();
  
    40
  
    } catch (IOException e) {
  
    41
  
    e.printStackTrace();
  
    42
  
    }
  
    43
  
    }
  
    44
  
    public static void main(String[] args) {
  
    45
  
    new DomParse();
  
    46
  
    }
  
    47 }
  
    4、代碼解釋
  
    先看看這個程序引用類:
  
    import java.io.FileInputStream;
  
    import java.io.FileNotFoundException;
  
    import java.io.IOException;
  
    import java.io.InputStream;
  
    import javax.xml.parsers.DocumentBuilder;
  
    import javax.xml.parsers.DocumentBuilderFactory;
  
    import javax.xml.parsers.ParserConfigurationException;
  
    //下面主要是org.xml.sax包的類
  
    import org.w3c.dom.Document;
  
    import org.w3c.dom.Element;
  
    import org.w3c.dom.Node;
  
    import org.w3c.dom.NodeList;
  
    import org.xml.sax.SAXException;
  
    上面那麼簡單的代碼一看就明白了,可是爲了介紹個DOM編程的大概仍是來看看這個程序吧:
  
    (1)獲得DOM解析器的工廠實例
  
    DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
  
    獲得javax.xml.parsers.DocumentBuilderFactory;類的實例就是咱們要的解析器工廠
  
    (2)從DOM工廠得到DOM解析器
  
    DocumentBuilder dombuilder=domfac.newDocumentBuilder();
  
    經過javax.xml.parsers.DocumentBuilderFactory實例的靜態方法newDocumentBuilder()獲得DOM解析器
  
    (3)把要解析的XML文檔轉化爲輸入流,以便DOM解析器解析它
  
    InputStream is=new FileInputStream("bin/library.xml");
  
    InputStream是一個接口。
  
    (4)解析XML文檔的輸入流,獲得一個Document
  
    Document doc=dombuilder.parse(is);
  
    由XML文檔的輸入流獲得一個org.w3c.dom.Document對象,之後的處理都是對Document對象進行的
  
    (5)獲得XML文檔的根節點
  
    Element root=doc.getDocumentElement();
  
    在DOM中只有根節點是一個org.w3c.dom.Element對象。
  
    (6)獲得節點的子節點
  
    NodeList
  
    books=root.getChildNodes();
  
    for(int i=0;i<books.getlength();i++){
  
    Node book=books.item(i);
  
    }
  
    這是用一個org.w3c.dom.NodeList接口來存放它全部子節點的,還有一種輪循子節點的方法,後面有介紹
  
    (7)取得節點的屬性值
  
    String email=book.getAttributes().getNamedItem("email").getNodeValue();
  
    System.out.println(email);
  
    注意,節點的屬性也是它的子節點。它的節點類型也是Node.ELEMENT_NODE
  
    (8)輪循子節點
  
    for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling()){
  
    if(node.getNodeType()==Node.ELEMENT_NODE){
  
    if(node.getNodeName().equals("name")){
  
    String name=node.getNodeValue();
  
    String name1=node.getFirstChild().getNodeValue();
  
    System.out.println(name);
  
    System.out.println(name1);
  
    }
  
    if(node.getNodeName().equals("price")){
  
    String price=node.getFirstChild().getNodeValue();
  
    System.out.println(price);
  
    }
  
    }
  
    這段代碼的打印輸出爲:
  
    null
  
    alterrjzjh
  
    jjjjjj
  
    從上面能夠看出
  
    String name=node.getNodeValue();
  
    是一個空值。而
  
    String name1=node.getFirstChild().getNodeValue();
  
    纔是真正的值,這是由於DOM把《name>rjzjh《/name>也看成是兩層結構的節點,其父節點 
  
   
   

 

#日誌日期:2008-5-25 星期日(Sunday) 晴

 

評論人: pizazzlk 評論日期:2008-5-25 15:55
  XML 文件以下:
  
  <?xml version='1.0' encoding='utf-8'?>
  <links>
  <link>
   <text>JSP Insider</text>
   <url>http://www.jspinsider.com</url>
   <date>
   <day>2</day>
   <month>1</month>
   <year>2001</year>
   </date>
  </link>
  
   <link>
   <text>ASP Insider</text>
   <url>http://www.Aspinsider.com</url>
   <date>
   <day>2</day>
   <month>1</month>
   <year>2001</year>
   </date>
   </link>
  </links>
  
  與XML對應的JAVA對象:
  
  package tiany.lijun.readxml;
  public class obj
   {
   String text=null;
   String url=null;
   Datee d=null;
   public obj()
   {
   d=new Datee();
   }
  public String getText()
  {
   return text;
  }
  public void setText(String text)
  {
   this.text = text;
  }
  public String getUrl()
  {
   return url;
  }
  public void setUrl(String url)
  {
   this.url = url;
  }
  public Datee getD()
  {
   return d;
  }
  public void setD(Datee d)
  {
   this.d = d;
  }
  
  
  public class Datee //內置對象 對應日期
  {
   String day=null;
   String month=null;
   String year=null;
   public String getDay()
   {
   return day;
   }
   public void setDay(String day)
   {
   this.day = day;
   }
   public String getMonth()
   {
   return month;
   }
   public void setMonth(String month)
   {
   this.month = month;
   }
   public String getYear()
   {
   return year;
   }
   public void setYear(String year)
   {
   this.year = year;
   }
   
  }
  
  
   }
  
  讀取XML的主文件:
  
  package tiany.lijun.readxml;
  
  import java.io.File;
  import java.io.IOException;
  import java.util.HashSet;
  import java.util.Iterator;
  import javax.xml.parsers.SAXParser;
  import javax.xml.parsers.SAXParserFactory;
  import org.xml.sax.Attributes;
  import org.xml.sax.SAXException;
  import org.xml.sax.helpers.DefaultHandler;
  
  public class readxml extends DefaultHandler
  {
   public obj vo;
   private String str;
   private HashSet set;
  
   public void endDocument() throws SAXException
   {
   }
  
   public void startDocument() throws SAXException
   {
  set = new HashSet();
   }
  
   public void startElement(String p0, String p1, String p2, Attributes p3) throws SAXException
   {
  if (p2.equals("link"))
  {
   vo = new obj();
  }
   }
  
   public void endElement(String p0, String p1, String p2) throws SAXException
   {
  if (p2.equals("text"))
  {
   vo.setText(str);
  }
  else if (p2.equals("url"))
  {
   vo.setUrl(str);
  }
  else if (p2.equals("link"))
  {
   set.add(vo);
   vo = null;
  }
  else if (p2.equals("links"))
  {
   display();
  }
  else if (p2.equals("day"))
  {
   vo.getD().setDay(str);
  }
  else if (p2.equals("month"))
  {
   vo.getD().setMonth(str);
  }
  else if (p2.equals("year"))
  {
   vo.getD().setYear(str);
  }
   }
  
   public void characters(char[] p0, int p1, int p2) throws SAXException
   {
  str = new String(p0, p1, p2);
   }
  
   public void display()
   {
  Iterator it = set.iterator();
  while (it.hasNext())
  {
   obj v = (obj) it.next();
   System.out.println(v.getText());
   System.out.println(v.getUrl());
   System.out.println(v.getD().getDay());
   System.out.println(v.getD().getMonth());
   System.out.println(v.getD().getYear());
   System.out.println("-------------------------------");
  }
   }
  
   static public void main(String[] args)
   {
  String filename = null;
  boolean validation = false;
  filename = "tomcat-usersw.xml";
  SAXParserFactory spf = SAXParserFactory.newInstance();
  SAXParser saxParser = null;
  
  try
  {
   saxParser = spf.newSAXParser();
  }
  catch (Exception ex)
  {
   System.err.println(ex);
   System.exit(1);
  }
  try
  {
   saxParser.parse(new File(filename), new readxml());
  }
  catch (SAXException se)
  {
   System.err.println(se.getMessage());
   System.exit(1);
  }
  catch (IOException ioe)
  {
   System.err.println(ioe);
   System.exit(1);
  }
   }
  
  }
  

評論人: pizazzlk 評論日期:2008-5-25 15:56
  回覆中爲SAX解析XML方式

評論人: pizazzlk 評論日期:2008-5-25 15:58
  JDOM解析XML文件
  
  
  二、jdom
  
  package org.lyj.xml;
  
  import org.jdom.output.Format;
  import org.jdom.Document;
  import java.io.IOException;
  import org.jdom.input.SAXBuilder;
  import org.jdom.output.XMLOutputter;
  import org.jdom.JDOMException;
  
  /**
   * <p>Title: </p>
   *
   * <p>Description: </p>
   *
   * <p>Copyright: Copyright (c) 2005</p>
   *
   * <p>Company: </p>
   *
   * @author not attributable
   * @version 1.0
   */
  public class JdomWriter {
   public JdomWriter() {
   }
  
   public void write(){
   try {
   SAXBuilder builder = new SAXBuilder();
   Document doc = builder.build("aa.xml");
   XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("utf-8"));
   outputter.output(doc, new java.io.FileOutputStream("bb.xml"));
   } catch (JDOMException e) {
   e.printStackTrace();
   } catch (IOException e) {
   e.printStackTrace();
   }
  
  
   }
   public static void main(String args[]){
   JdomWriter jd = new JdomWriter();
   jd.write();
   }
  }
  
  
  
    

評論人: pizazzlk 評論日期:2008-5-25 16:00
  Java解析XML文件2007-08-17 11:17package com.yc.ycportal.ge.util;      import java.io.FileInputStream;   import java.util.Enumeration;   import java.util.List;   import java.util.Properties;   import java.util.ResourceBundle;      import javax.xml.parsers.SAXParser;   import javax.xml.parsers.SAXParserFactory;      import org.jdom.Document;   import org.jdom.Element;   import org.jdom.input.SAXBuilder;   import org.xml.sax.Attributes;   import org.xml.sax.SAXException;   import org.xml.sax.helpers.DefaultHandler;      /**   * @author    * 本類的做用是對properties和xml文件的解析,重點在於包括xml文件的兩種解析方式   * 如今有三種用於Java的流行xml解析技術,文檔對象模型(Document Object Model,DOM),基於W3C的   * 成熟標準,二、用於XML的簡單API(Simple API for XML),第一個被普遍採用的用Java編寫的XML API   * 是一個事實上的標準,3、用於XML的數據流API(Straming API for XML,StAX),JSR-173中採用   * 的一個新解析模型   */   public class ParseFile {      public static ParseFile getInterface(){    return new ParseFile();   }      /**解析Properties文件獲取數據信息*/   /**    *properties的文件格式爲    *username=sa    *userpass=123以第一等號爲標準,後面爲它的值     */   public List getPropertes(String fileName){    List list = null;    ResourceBundle rb = ResourceBundle.getBundle(fileName);    list.add(rb.getString("username"));    list.add(rb.getString("userpass"));    return list;   }   /**用SAX方式解析XML文件獲取數據信息,建立一個解析XML文件的內部類解析器*/   class ParseXML extends DefaultHandler{    //全部的方法是子類重寫父類的方法    String currentName = null;    StringBuffer currentValue = new StringBuffer();    Properties properties = null;        //接收元素開始的通知。     //默認狀況下,不執行任何操做。應用程序編寫者能夠在子類中重寫此方法,以便在每一個元素的開始處採起特定的操做    public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException{    this.currentValue.delete(0, this.currentValue.length());    this.currentName = qName;    }    //接收元素中字符數據的通知    //默認狀況下,不執行任何操做。應用程序編寫者能夠重寫此方法,以便對每塊字符數據採起特定的措施    //如將該數據添加到節點或緩衝區,或者將該數據打印到文件。    public void characters(char[] ch,int start,int length)throws SAXException{    this.currentValue.append(ch,start,length);    }    //接收元素結束的通知    //默認狀況下,不執行任何操做。應用程序編寫者能夠在子類中重寫此方法,以便在每一個元素的結束處採起特定的操做    //如,結束樹節點或將輸出寫入文件。    public void endElement(String uri,String localName,String qName)throws SAXException{    this.properties.put(qName.toLowerCase(), this.currentValue.toString().trim());    }    //返回存儲XML信息數據的properties    public Properties getProperties(){    return this.properties;    }   }   public List getSAXXml(String fileName)throws Exception{    List list = null;    ParseXML parsexml = new ParseXML();    Properties properties = null;    SAXParserFactory factory = SAXParserFactory.newInstance();    //若是由此代碼生成的解析器將提供對 XML 名稱空間的支持,則爲 true;不然爲 false。    factory.setNamespaceAware(false);    //指定由此代碼生成的解析器將驗證被解析的文檔。默認狀況下,其值設置爲 false    factory.setValidating(false);    SAXParser parser = factory.newSAXParser();    //使用指定的DefaultHandler將指定文件的內容解析爲 XML。    parser.parse(fileName, parsexml);    properties = parsexml.getProperties();    Enumeration em = properties.keys();    while(em.hasMoreElements()){    list.add(properties.get(em.nextElement().toString()));    }    return list;   }   /**用Dom方式解析XML文件獲取數據信息,比較容易理解和掌握的一種方式very good*/   public List getDOMXml(String fileName)throws Exception{    List list = null;    SAXBuilder builder = new SAXBuilder();    Document document = builder.build(new FileInputStream(fileName));    //document.getRootElement()獲取根節點返回一個Element    List listchild = document.getRootElement().getChildren("table");    for(int i=0;i<listchild.size();i++){    Element e = (Element)listchild.get(i);    String tableName = e.getChild("tablename").getText();    List nextchild = e.getChild("fields").getChildren("field");    list.add(tableName);    for(int j=0;j<nextchild.size();j++){    Element child = (Element)nextchild.get(j);    list.add(child.getAttributeValue("name"));    }    }    //返回的List的結構是以表名爲0個索引位置後面依次爲表的字段名稱,附帶XML文件描述    return list;   }   }         <?xml version="1.0" encoding="gb2312" ?>   <tables>   <table>     <tablename>dic_rate_zhwd</tablename>    <fields>    <field name="organ_id" type="string"/>    <field name="business_id" type="string"/>    <field name="business_name" type="string"/>    <field name="rate" type="double"/>    </fields>   </table>   </tables>       
相關文章
相關標籤/搜索