sax和dom解析xml文件_第1頁(yè)
sax和dom解析xml文件_第2頁(yè)
sax和dom解析xml文件_第3頁(yè)
sax和dom解析xml文件_第4頁(yè)
sax和dom解析xml文件_第5頁(yè)
已閱讀5頁(yè),還剩8頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、XMLS不同的語(yǔ)言里解析方式都是一樣的,只不過(guò)實(shí)現(xiàn)的語(yǔ)法不同而已。基本的解析方式有兩種,一種叫SAX另一種叫DOM SAX是基于事件流的解析,DOM是基于XML文檔樹(shù)結(jié)構(gòu)的解析。假設(shè)我們 XMM內(nèi)容和結(jié)構(gòu)如下<?xml version="1.0" encoding="UTF-8"?>(employees)(employee)<name>ddviplinux</name><sex>m</sex><age>30</age>(/employee)(/employees)本文使用

2、JAVA語(yǔ)言來(lái)實(shí)現(xiàn)DOMf SAX的XML文檔生成與解析。首先定義一個(gè)操作 XM墳檔的接口 XmlDocument它定義了 XML文檔的建立與解析的接口package com.alisoft.facepay.framework.bean;/*author hongliang.dinghl定義XML文檔建立與解析的接口*/public interface XmlDocument /*建立XML文檔param fileName文件全路徑名稱*/public void createXml(String fileName);/*解析XML文檔param fileName文件全路徑名稱*/public

3、void parserXml(String fileName);1.DOM生成和解析XML文檔DOM接為XML文檔的已解析版本定義了一組接口。解析器讀入整個(gè)文檔,然后構(gòu)建一個(gè)駐留內(nèi)存的樹(shù)結(jié)構(gòu),然后代碼就可以使用口來(lái)操作這個(gè)樹(shù)結(jié)構(gòu)。優(yōu)點(diǎn):整個(gè)文檔樹(shù)在內(nèi)存中,便于操作;支持刪除、修改、重新排列等多種功能;缺點(diǎn):將整個(gè)文檔調(diào)入內(nèi)存(包括無(wú)用的節(jié)點(diǎn)),浪費(fèi)時(shí)間和空間;使用場(chǎng)合:一旦解析了文檔還需多次訪問(wèn)這些數(shù)據(jù);硬件資源充足(內(nèi)存、CPU。package com.alisoft.facepay.framework.bean;import java.io.FileInputStream;import j

4、ava.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xm

5、l.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamRe

6、sult;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;/* author hongliang.dinghl* DOM生成與解析XML文檔*/public class DomDemo implements XmlDocument private Document document;private String fileName;public void init()

7、try DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();this.document = builder.newDocument(); catch (ParserConfigurationException e) System.out.println(e.getMessage();public void createXml(String fileName) Element root = this.

8、document.createElement("employees");this.document.appendChild(root);Element employee = this.document.createElement("employee");Element name = this.document.createElement("name");name.appendChild(this.document.createTextNode("丁宏亮");employee.appendChild(name);El

9、ement sex = this.document.createElement("sex");sex.appendChild(this.document.createTextNode("m");employee.appendChild(sex);Element age = this.document.createElement("age");age.appendChild(this.document.createTextNode("30");employee.appendChild(age);root.append

10、Child(employee);TransformerFactory tf = TransformerFactory.newInstance();try Transformer transformer = tf.newTransformer();DOMSource source = new DOMSource(document);transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");transformer.setOutputProperty(OutputKeys.INDENT, "yes"

11、;);PrintWriter pw = new PrintWriter(new FileOutputStream(fileName);StreamResult result = new StreamResult(pw);transformer.transform(source, result);System.out.println(" 生成 XML文件成功!”); catch (TransformerConfigurationException e) System.out.println(e.getMessage(); catch (IllegalArgumentException

12、e) System.out.println(e.getMessage(); catch (FileNotFoundException e) System.out.println(e.getMessage(); catch (TransformerException e) System.out.println(e.getMessage();public void parserXml(String fileName) try DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db =

13、dbf.newDocumentBuilder();Document document = db.parse(fileName);NodeList employees = document.getChildNodes();for (int i = 0; i < employees.getLength(); i+) Node employee = employees.item(i);NodeList employeeInfo = employee.getChildNodes();for (int j = 0; j < employeeInfo.getLength(); j+) Node

14、 node = employeeInfo.item(j);NodeList employeeMeta = node.getChildNodes();for (int k = 0; k < employeeMeta.getLength(); k+) System.out.println(employeeMeta.item(k).getNodeName()+ ":" + employeeMeta.item(k).getTextContent();System.out.println(" 解析完畢"); catch (FileNotFoundExcept

15、ion e) System.out.println(e.getMessage(); catch (ParserConfigurationException e) System.out.println(e.getMessage(); catch (SAXException e) System.out.println(e.getMessage(); catch (IOException e) System.out.println(e.getMessage(); 2.SAX生成和解析XML文檔為解決DOM勺問(wèn)題,出現(xiàn)了 SAX SAX ,事件驅(qū)動(dòng)。當(dāng)解析器發(fā)現(xiàn)元素開(kāi)始、元素結(jié)束、文本、文檔的開(kāi)始或結(jié)

16、束等時(shí),發(fā)送事件, 程序員編寫響應(yīng)這些事件的代碼,保存數(shù)據(jù)。優(yōu)點(diǎn):不用事先調(diào)入整個(gè)文檔,占用資源少;SAX解析器彳t碼比DOM?析器代碼小,適于Applet ,下載。缺點(diǎn):不是持久的;事件過(guò)后,若沒(méi)保存數(shù)據(jù),那么數(shù)據(jù)就丟了;無(wú)狀態(tài)性;從事件中只能得到文本,但不知該文本屬 于哪個(gè)元素;使用場(chǎng)合: Applet;只需XML文檔的少量?jī)?nèi)容,很少回頭訪問(wèn);機(jī)器內(nèi)存少;Java代碼package com.alisoft.facepay.framework.bean;import java.io.FileInputStream;import java.io.FileNotFoundException;im

17、port java.io.IOException;import java.io.InputStream;import javax.xml.parsers.ParserConfigurationException;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;/* author hon

18、gliang.dinghl* SAX文檔解析*/public class SaxDemo implements XmlDocument public void createXml(String fileName) System.out.println("<<"+filename+">>"); public void parserXml(String fileName) SAXParserFactory saxfac = SAXParserFactory.newInstance();try SAXParser saxparser =

19、 saxfac.newSAXParser();Inputstream is = new FilelnputStream(fileName);saxparser.parse(is, new MySAXHandler(); catch (ParserConfigurationException e) e.printStackTrace(); catch (SAXException e) e.printStackTrace(); catch (FileNotFoundException e) e.printStackTrace(); catch (IOException e) e.printStac

20、kTrace();class MySAXHandler extends DefaultHandler boolean hasAttribute = false;Attributes attributes = null;public void startDocument() throws SAXException public void endDocument() throws SAXException System.out.println("文檔開(kāi)始打印了");System.out.println("文檔打印結(jié)束了 ");public void star

21、tElement(String uri, String localName, String qName,Attributes attributes) throws SAXException if (qName.equals("employees") return;if (qName.equals("employee") System.out.println(qName);if (attributes.getLength() > 0) this.attributes = attributes;this.hasAttribute = true; pub

22、lic void endElement(String uri, String localName, String qName) throws SAXException if (hasAttribute && (attributes != null) for (int i = 0; i < attributes.getLength(); i+) System.out.println(attributes.getQName(0)+ attributes.getValue(0); public void characters(char口 ch, int start, int l

23、ength)throws SAXException System.out.println(new String(ch, start, length);package com.alisoft.facepay.framework.bean;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import javax.xml.parsers.ParserConfigurationException;import

24、 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;/* author hongliang.dinghl* SAX文檔解析*/public class SaxDemo implements XmlDocument public void createXml(String fileName) Syste

25、m.out.println("<<"+filename+">>");public void parserXml(String fileName) SAXParserFactory saxfac = SAXParserFactory.newInstance();try SAXParser saxparser = saxfac.newSAXParser();InputStream is = new FileInputStream(fileName);saxparser.parse(is, new MySAXHandler(); cat

26、ch (ParserConfigurationException e) e.printStackTrace(); catch (SAXException e) e.printStackTrace(); catch (FileNotFoundException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); class MySAXHandler extends DefaultHandler boolean hasAttribute = false;Attributes attributes = null; pu

27、blic void startDocument() throws SAXException System.out.println("文檔開(kāi)始打印了 "); public void endDocument() throws SAXException System.out.println("文檔打印結(jié)束了 "); public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException if (qName.equ

28、als("employees") return; if (qName.equals("employee") System.out.println(qName);if (attributes.getLength() > 0) this.attributes = attributes;this.hasAttribute = true; public void endElement(String uri, String localName, String qName) throws SAXException if (hasAttribute &&

29、amp; (attributes != null) for (int i = 0; i < attributes.getLength(); i+) System.out.println(attributes.getQName(0)+ attributes.getValue(0); public void characters(char口 ch, int start, int length) throws SAXException System.out.println(new String(ch, start, length); 3 .DOM4J生成和解析XM戊檔DOM4謠一個(gè)非常非常優(yōu)秀

30、的Java XMLAPI,具有性能優(yōu)異、功能強(qiáng)大和極端易用使用的特點(diǎn),同時(shí)它也是一個(gè)開(kāi)放源代碼的軟件。如今你可以看到越來(lái)越多的 Java 軟件都在使用 DOM4J來(lái)讀寫XML,特別值得一提的是連 Sun的JAXM也在用DOM4JJava代碼package com.alisoft.facepay.framework.bean;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.Writer;import java.util.Iterator;import org.dom4j

31、.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;/* author hongliang.dinghl* Dom4j生成XML文檔與解析XML文檔*/public class Dom4jDemo implements XmlDocument public void createXml(String fileName) Doc

32、ument document = DocumentHelper.createDocument();Element employees=document.addElement("employees");Element employee=employees.addElement("employee");Element name= employee.addElement("name");name.setText("ddvip");Element sex=employee.addElement("sex"

33、;);sex.setText("m");Element age=employee.addElement("age");age.setText("29");try Writer fileWriter=new FileWriter(fileName);XMLWriter xmlWriter=new XMLWriter(fileWriter);xmlWriter.write(document);xmlWriter.close(); catch (IOException e) System.out.println(e.getMessage()

34、;public void parserXml(String fileName) File inputXml=new File(fileName);SAXReader saxReader = new SAXReader();try Document document = saxReader.read(inputXml);Element employees=document.getRootElement();for(Iterator i = employees.elementIterator(); i.hasNext();)Element employee = (Element) i.next()

35、;for(Iterator j = employee.elementIterator(); j.hasNext();)Element node=(Element) j.next();System.out.println(node.getName()+":"+node.getText(); catch (DocumentException e) System.out.println(e.getMessage();System.out.println("dom4j parserXml"); 4 .JDOM生成和解析XML為減少DOM SAX的編碼量,出現(xiàn)了

36、JDOM優(yōu)點(diǎn):20-80原則,極大減少了代碼量。使用場(chǎng)合:要實(shí)現(xiàn)的功能簡(jiǎn)單,如解析、創(chuàng)建等, 但在底層,JDOMS是使用SAX(最常用)、DOM Xanan文檔。package com.alisoft.facepay.framework.bean;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;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;/* author hongliang.dinghl* JDOM生成與解析XML文檔*/public class JDomDemo implements XmlDocument public void creat

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論