日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

Java解析XML汇总(DOM/SAX/JDOM/DOM4j/XPath)

發布時間:2024/4/17 asp.net 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java解析XML汇总(DOM/SAX/JDOM/DOM4j/XPath) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

http://blog.csdn.net/smcwwh/article/details/7183869

關鍵字:Java解析xml、解析xml四種方法、DOM、SAX、JDOM、DOM4j、XPath

【引言】

目前在Java中用于解析XML的技術很多,主流的有DOM、SAX、JDOM、DOM4j,下文主要介紹這4種解析XML文檔技術的使用、優缺點及性能測試。

一、【基礎知識——掃盲】

sax、dom是兩種對xml文檔進行解析的方法(沒有具體實現,只是接口),所以只有它們是無法解析xml文檔的;jaxp只是api,它進一步封裝了sax、dom兩種接口,并且提供了DomcumentBuilderFactory/DomcumentBuilder和SAXParserFactory/SAXParser(默認使用xerces解釋器)。

二、【DOM、SAX、JDOM、DOM4j簡單使用介紹】

1、【DOM(Document Object Model) 】
由W3C提供的接口,它將整個XML文檔讀入內存,構建一個DOM樹來對各個節點(Node)進行操作。
示例代碼:

[html] view plaincopyprint?
  • <?xml version="1.0" encoding="UTF-8"?> <university name="pku"><college name="c1"><class name="class1"><student name="stu1" sex='male' age="21" /><student name="stu2" sex='female' age="20" /><student name="stu3" sex='female' age="20" /></class><class name="class2"><student name="stu4" sex='male' age="19" /><student name="stu5" sex='female' age="20" /><student name="stu6" sex='female' age="21" /></class></college><college name="c2"><class name="class3"><student name="stu7" sex='male' age="20" /></class></college><college name="c3"></college> </university>

    后文代碼中有使用到text.xml(該文檔放在src路徑下,既編譯后在classes路徑下),都是指該xml文檔。

    [java] view plaincopyprint? package test.xml;import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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.StreamResult;import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException;/*** dom讀寫xml* @author whwang*/ public class TestDom {public static void main(String[] args) {read();//write();}public static void read() {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();try {DocumentBuilder builder = dbf.newDocumentBuilder();InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");Document doc = builder.parse(in);// root <university>Element root = doc.getDocumentElement();if (root == null) return;System.err.println(root.getAttribute("name"));// all college nodeNodeList collegeNodes = root.getChildNodes();if (collegeNodes == null) return;for(int i = 0; i < collegeNodes.getLength(); i++) {Node college = collegeNodes.item(i);if (college != null && college.getNodeType() == Node.ELEMENT_NODE) {System.err.println("\t" + college.getAttributes().getNamedItem("name").getNodeValue());// all class nodeNodeList classNodes = college.getChildNodes();if (classNodes == null) continue;for (int j = 0; j < classNodes.getLength(); j++) {Node clazz = classNodes.item(j);if (clazz != null && clazz.getNodeType() == Node.ELEMENT_NODE) {System.err.println("\t\t" + clazz.getAttributes().getNamedItem("name").getNodeValue());// all student nodeNodeList studentNodes = clazz.getChildNodes();if (studentNodes == null) continue;for (int k = 0; k < studentNodes.getLength(); k++) {Node student = studentNodes.item(k);if (student != null && student.getNodeType() == Node.ELEMENT_NODE) {System.err.print("\t\t\t" + student.getAttributes().getNamedItem("name").getNodeValue());System.err.print(" " + student.getAttributes().getNamedItem("sex").getNodeValue());System.err.println(" " + student.getAttributes().getNamedItem("age").getNodeValue());}}}}}}} catch (ParserConfigurationException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void write() {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();try {DocumentBuilder builder = dbf.newDocumentBuilder();InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");Document doc = builder.parse(in);// root <university>Element root = doc.getDocumentElement();if (root == null) return;// 修改屬性root.setAttribute("name", "tsu");NodeList collegeNodes = root.getChildNodes();if (collegeNodes != null) {for (int i = 0; i <collegeNodes.getLength() - 1; i++) {// 刪除節點Node college = collegeNodes.item(i);if (college.getNodeType() == Node.ELEMENT_NODE) {String collegeName = college.getAttributes().getNamedItem("name").getNodeValue();if ("c1".equals(collegeName) || "c2".equals(collegeName)) {root.removeChild(college);} else if ("c3".equals(collegeName)) {Element newChild = doc.createElement("class");newChild.setAttribute("name", "c4");college.appendChild(newChild);}}}}// 新增節點Element addCollege = doc.createElement("college");addCollege.setAttribute("name", "c5");root.appendChild(addCollege);Text text = doc.createTextNode("text");addCollege.appendChild(text);// 將修改后的文檔保存到文件TransformerFactory transFactory = TransformerFactory.newInstance();Transformer transFormer = transFactory.newTransformer();DOMSource domSource = new DOMSource(doc);File file = new File("src/dom-modify.xml");if (file.exists()) {file.delete();}file.createNewFile();FileOutputStream out = new FileOutputStream(file); StreamResult xmlResult = new StreamResult(out);transFormer.transform(domSource, xmlResult);System.out.println(file.getAbsolutePath());} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (TransformerConfigurationException e) {e.printStackTrace();} catch (TransformerException e) {e.printStackTrace();}} }

    該代碼只要稍做修改,即可變得更加簡潔,無需一直寫if來判斷是否有子節點。

    2、【SAX (Simple API for XML) 】
    SAX不用將整個文檔加載到內存,基于事件驅動的API(Observer模式),用戶只需要注冊自己感興趣的事件即可。SAX提供EntityResolver, DTDHandler, ContentHandler, ErrorHandler接口,分別用于監聽解析實體事件、DTD處理事件、正文處理事件和處理出錯事件,與AWT類似,SAX還提供了一個對這4個接口默認的類DefaultHandler(這里的默認實現,其實就是一個空方法),一般只要繼承DefaultHandler,重寫自己感興趣的事件即可。
    示例代碼:

    [java] view plaincopyprint? package test.xml;import 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.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler;/**** @author whwang*/ public class TestSAX {public static void main(String[] args) {read();write();}public static void read() {try {SAXParserFactory factory = SAXParserFactory.newInstance();SAXParser parser = factory.newSAXParser();InputStream in = TestSAX.class.getClassLoader().getResourceAsStream("test.xml");parser.parse(in, new MyHandler());} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void write() {System.err.println("純SAX對于寫操作無能為力");}}// 重寫對自己感興趣的事件處理方法 class MyHandler extends DefaultHandler {@Overridepublic InputSource resolveEntity(String publicId, String systemId)throws IOException, SAXException {return super.resolveEntity(publicId, systemId);}@Overridepublic void notationDecl(String name, String publicId, String systemId)throws SAXException {super.notationDecl(name, publicId, systemId);}@Overridepublic void unparsedEntityDecl(String name, String publicId,String systemId, String notationName) throws SAXException {super.unparsedEntityDecl(name, publicId, systemId, notationName);}@Overridepublic void setDocumentLocator(Locator locator) {super.setDocumentLocator(locator);}@Overridepublic void startDocument() throws SAXException {System.err.println("開始解析文檔");}@Overridepublic void endDocument() throws SAXException {System.err.println("解析結束");}@Overridepublic void startPrefixMapping(String prefix, String uri)throws SAXException {super.startPrefixMapping(prefix, uri);}@Overridepublic void endPrefixMapping(String prefix) throws SAXException {super.endPrefixMapping(prefix);}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {System.err.print("Element: " + qName + ", attr: ");print(attributes);}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {super.endElement(uri, localName, qName);}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {super.characters(ch, start, length);}@Overridepublic void ignorableWhitespace(char[] ch, int start, int length)throws SAXException {super.ignorableWhitespace(ch, start, length);}@Overridepublic void processingInstruction(String target, String data)throws SAXException {super.processingInstruction(target, data);}@Overridepublic void skippedEntity(String name) throws SAXException {super.skippedEntity(name);}@Overridepublic void warning(SAXParseException e) throws SAXException {super.warning(e);}@Overridepublic void error(SAXParseException e) throws SAXException {super.error(e);}@Overridepublic void fatalError(SAXParseException e) throws SAXException {super.fatalError(e);}private void print(Attributes attrs) {if (attrs == null) return;System.err.print("[");for (int i = 0; i < attrs.getLength(); i++) {System.err.print(attrs.getQName(i) + " = " + attrs.getValue(i));if (i != attrs.getLength() - 1) {System.err.print(", ");}}System.err.println("]");} }

    3、【JDOM】
    JDOM與DOM非常類似,它是處理XML的純JAVA API,API大量使用了Collections類,且JDOM僅使用具體類而不使用接口。 JDOM 它自身不包含解析器。它通常使用 SAX2 解析器來解析和驗證輸入 XML 文檔(盡管它還可以將以前構造的 DOM 表示作為輸入)。它包含一些轉換器以將 JDOM 表示輸出成 SAX2 事件流、DOM 模型或 XML 文本文檔
    示例代碼:

    [java] view plaincopyprint? package test.xml;import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List;import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter;/*** JDom讀寫xml* @author whwang*/ public class TestJDom {public static void main(String[] args) {//read();write();}public static void read() {try {boolean validate = false;SAXBuilder builder = new SAXBuilder(validate);InputStream in = TestJDom.class.getClassLoader().getResourceAsStream("test.xml");Document doc = builder.build(in);// 獲取根節點 <university>Element root = doc.getRootElement();readNode(root, "");} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@SuppressWarnings("unchecked")public static void readNode(Element root, String prefix) {if (root == null) return;// 獲取屬性List<Attribute> attrs = root.getAttributes();if (attrs != null && attrs.size() > 0) {System.err.print(prefix);for (Attribute attr : attrs) {System.err.print(attr.getValue() + " ");}System.err.println();}// 獲取他的子節點List<Element> childNodes = root.getChildren();prefix += "\t";for (Element e : childNodes) {readNode(e, prefix);}}public static void write() {boolean validate = false;try {SAXBuilder builder = new SAXBuilder(validate);InputStream in = TestJDom.class.getClassLoader().getResourceAsStream("test.xml");Document doc = builder.build(in);// 獲取根節點 <university>Element root = doc.getRootElement();// 修改屬性root.setAttribute("name", "tsu");// 刪除boolean isRemoved = root.removeChildren("college");System.err.println(isRemoved);// 新增Element newCollege = new Element("college");newCollege.setAttribute("name", "new_college");Element newClass = new Element("class");newClass.setAttribute("name", "ccccc");newCollege.addContent(newClass);root.addContent(newCollege);XMLOutputter out = new XMLOutputter();File file = new File("src/jdom-modify.xml");if (file.exists()) {file.delete();}file.createNewFile();FileOutputStream fos = new FileOutputStream(file);out.output(doc, fos);} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

    4、【DOM4j】
    dom4j是目前在xml解析方面是最優秀的(Hibernate、Sun的JAXM也都使用dom4j來解析XML),它合并了許多超出基本 XML 文檔表示的功能,包括集成的 XPath 支持、XML Schema 支持以及用于大文檔或流化文檔的基于事件的處理
    示例代碼:

    [java] view plaincopyprint? package test.xml;import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; 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.ProcessingInstruction; import org.dom4j.VisitorSupport; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter;/*** Dom4j讀寫xml* @author whwang*/ public class TestDom4j {public static void main(String[] args) {read1();//read2();//write();}public static void read1() {try {SAXReader reader = new SAXReader();InputStream in = TestDom4j.class.getClassLoader().getResourceAsStream("test.xml");Document doc = reader.read(in);Element root = doc.getRootElement();readNode(root, "");} catch (DocumentException e) {e.printStackTrace();}}@SuppressWarnings("unchecked")public static void readNode(Element root, String prefix) {if (root == null) return;// 獲取屬性List<Attribute> attrs = root.attributes();if (attrs != null && attrs.size() > 0) {System.err.print(prefix);for (Attribute attr : attrs) {System.err.print(attr.getValue() + " ");}System.err.println();}// 獲取他的子節點List<Element> childNodes = root.elements();prefix += "\t";for (Element e : childNodes) {readNode(e, prefix);}}public static void read2() {try {SAXReader reader = new SAXReader();InputStream in = TestDom4j.class.getClassLoader().getResourceAsStream("test.xml");Document doc = reader.read(in);doc.accept(new MyVistor());} catch (DocumentException e) {e.printStackTrace();}}public static void write() {try {// 創建一個xml文檔Document doc = DocumentHelper.createDocument();Element university = doc.addElement("university");university.addAttribute("name", "tsu");// 注釋university.addComment("這個是根節點");Element college = university.addElement("college");college.addAttribute("name", "cccccc");college.setText("text");File file = new File("src/dom4j-modify.xml");if (file.exists()) {file.delete();}file.createNewFile();XMLWriter out = new XMLWriter(new FileWriter(file));out.write(doc);out.flush();out.close();} catch (IOException e) {e.printStackTrace();}} }class MyVistor extends VisitorSupport {public void visit(Attribute node) {System.out.println("Attibute: " + node.getName() + "="+ node.getValue());}public void visit(Element node) {if (node.isTextOnly()) {System.out.println("Element: " + node.getName() + "="+ node.getText());} else {System.out.println(node.getName());}}@Overridepublic void visit(ProcessingInstruction node) {System.out.println("PI:" + node.getTarget() + " " + node.getText());} }

    三、【性能測試】

    環境:AMD4400+ 2.0+GHz主頻 JDK6.0
    運行參數:-Xms400m -Xmx400m
    xml文件大小:10.7M
    結果:
    DOM: >581297ms
    SAX: 8829ms
    JDOM: 581297ms
    DOM4j: 5309ms
    時間包括IO的,只是進行了簡單的測試,僅供參考!!!!

    四、【對比】

    1、【DOM】
    DOM是基于樹的結構,通常需要加載整文檔和構造DOM樹,然后才能開始工作。
    優點:
    ?? ?a、由于整棵樹在內存中,因此可以對xml文檔隨機訪問
    ?? ?b、可以對xml文檔進行修改操作
    ?? ?c、較sax,dom使用也更簡單。
    缺點:
    ?? ?a、整個文檔必須一次性解析完
    ?? ?a、由于整個文檔都需要載入內存,對于大文檔成本高
    2、【SAX】
    SAX類似流媒體,它基于事件驅動的,因此無需將整個文檔載入內存,使用者只需要監聽自己感興趣的事件即可。
    優點:
    ?? ?a、無需將整個xml文檔載入內存,因此消耗內存少
    ?? ?b、可以注冊多個ContentHandler
    缺點:
    ?? ?a、不能隨機的訪問xml中的節點
    ?? ?b、不能修改文檔
    3、【JDOM】
    JDOM是純Java的處理XML的API,其API中大量使用Collections類,
    優點:
    ?? ?a、DOM方式的優點
    ?? ?b、具有SAX的Java規則
    缺點
    ?? ?a、DOM方式的缺點
    4、【DOM4J】
    這4中xml解析方式中,最優秀的一個,集易用和性能于一身。

    五、【小插曲XPath】

    XPath 是一門在 XML 文檔中查找信息的語言, 可用來在 XML 文檔中對元素和屬性進行遍歷。XPath 是 W3C XSLT 標準的主要元素,并且 XQuery 和 XPointer 同時被構建于 XPath 表達之上。因此,對 XPath 的理解是很多高級 XML 應用的基礎。
    XPath非常類似對數據庫操作的SQL語言,或者說JQuery,它可以方便開發者抓起文檔中需要的東西。(dom4j也支持xpath)
    示例代碼:

    [java] view plaincopyprint? package test.xml;import java.io.IOException; import java.io.InputStream;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;public class TestXPath {public static void main(String[] args) {read();}public static void read() {try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder builder = dbf.newDocumentBuilder();InputStream in = TestXPath.class.getClassLoader().getResourceAsStream("test.xml");Document doc = builder.parse(in);XPathFactory factory = XPathFactory.newInstance();XPath xpath = factory.newXPath();// 選取所有class元素的name屬性// XPath語法介紹: http://w3school.com.cn/xpath/XPathExpression expr = xpath.compile("//class/@name");NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);for (int i = 0; i < nodes.getLength(); i++) {System.out.println("name = " + nodes.item(i).getNodeValue());}} catch (XPathExpressionException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

    六、【補充】

    注意4種解析方法對TextNode(文本節點)的處理:

    1、在使用DOM時,調用node.getChildNodes()獲取該節點的子節點,文本節點也會被當作一個Node來返回,如:

    [html] view plaincopyprint? <?xml version="1.0" encoding="UTF-8"?> <university name="pku"><college name="c1"><class name="class1"><student name="stu1" sex='male' age="21" /><student name="stu2" sex='female' age="20" /><student name="stu3" sex='female' age="20" /></class></college> </university> [java] view plaincopyprint? package test.xml;import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;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讀寫xml* @author whwang*/ public class TestDom2 {public static void main(String[] args) {read();}public static void read() {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();try {DocumentBuilder builder = dbf.newDocumentBuilder();InputStream in = TestDom2.class.getClassLoader().getResourceAsStream("test.xml");Document doc = builder.parse(in);// root <university>Element root = doc.getDocumentElement();if (root == null) return; // System.err.println(root.getAttribute("name"));// all college nodeNodeList collegeNodes = root.getChildNodes();if (collegeNodes == null) return;System.err.println("university子節點數:" + collegeNodes.getLength());System.err.println("子節點如下:");for(int i = 0; i < collegeNodes.getLength(); i++) {Node college = collegeNodes.item(i);if (college == null) continue;if (college.getNodeType() == Node.ELEMENT_NODE) {System.err.println("\t元素節點:" + college.getNodeName());} else if (college.getNodeType() == Node.TEXT_NODE) {System.err.println("\t文本節點:" + Arrays.toString(college.getTextContent().getBytes()));}}} catch (ParserConfigurationException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }

    輸出的結果是:

    [java] view plaincopyprint? university子節點數:3 子節點如下:文本節點:[10, 9]元素節點:college文本節點:[10]

    其中\n的ASCII碼為10,\t的ASCII碼為9。結果讓人大吃一驚,university的子節點數不是1,也不是2,而是3,這3個子節點都是誰呢?為了看得更清楚點,把xml文檔改為:

    [html] view plaincopyprint? <?xml version="1.0" encoding="UTF-8"?> <university name="pku">11<college name="c1"><class name="class1"><student name="stu1" sex='male' age="21" /><student name="stu2" sex='female' age="20" /><student name="stu3" sex='female' age="20" /></class></college>22 </university>

    還是上面的程序,輸出結果為:

    [java] view plaincopyprint? university子節點數:3 子節點如下:文本節點:[49, 49, 10, 9]元素節點:college文本節點:[50, 50, 10]

    其中數字1的ASCII碼為49,數字2的ASCII碼為50。

    2、使用SAX來解析同DOM,當你重寫它的public void characters(char[] ch, int start, int length)方法時,你就能看到。

    3、JDOM,調用node.getChildren()只返回子節點,不包括TextNode節點(不管該節點是否有Text信息)。如果要獲取該節點的Text信息,可以調用node.getText()方法,該方法返回節點的Text信息,也包括\n\t等特殊字符。

    4、DOM4j同JDOM

    參考:

    http://www.docin.com/p-78963650.html

    http://wenku.baidu.com/view/b091f9360b4c2e3f5727638b.html

    http://kree.iteye.com/blog/668280

    ?

    ?

    ?

    詳解Java解析XML的四種方法

    http://developer.51cto.com/art/200903/117512.htm

    XML現在已經成為一種通用的數據交換格式,它的平臺無關性,語言無關性,系統無關性,給數據集成與交互帶來了極大的方便。對于XML本身的語法知識與技術細節,需要閱讀相關的技術文獻,這里面包括的內容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations),具體可參閱w3c官方網站文檔http://www.w3.org獲取更多信息。

    XML在不同的語言里解析方式都是一樣的,只不過實現的語法不同而已。基本的解析方式有兩種,一種叫SAX,另一種叫DOM。SAX是基于事件流的解析,DOM是基于XML文檔樹結構的解析。假設我們XML的內容和結構如下:?

    <?xml version="1.0" encoding="UTF-8"?> <employees> <employee> <name>ddviplinux</name> <sex>m</sex> <age>30</age> </employee> </employees>

    本文使用JAVA語言來實現DOM與SAX的XML文檔生成與解析。
    首先定義一個操作XML文檔的接口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 void parserXml(String fileName); }

    1.DOM生成和解析XML文檔

    為 XML 文檔的已解析版本定義了一組接口。解析器讀入整個文檔,然后構建一個駐留內存的樹結構,然后代碼就可以使用 DOM 接口來操作這個樹結構。優點:整個文檔樹在內存中,便于操作;支持刪除、修改、重新排列等多種功能;缺點:將整個文檔調入內存(包括無用的節點),浪費時間和空間;使用場合:一旦解析了文檔還需多次訪問這些數據;硬件資源充足(內存、CPU)。?

    package com.alisoft.facepay.framework.bean; import java.io.FileInputStream; import java.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.xml.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.StreamResult; 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() { 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.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); Element 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.appendChild(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"); 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 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 = 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 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 (FileNotFoundException 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的問題,出現了SAX。SAX ,事件驅動。當解析器發現元素開始、元素結束、文本、文檔的開始或結束等時,發送事件,程序員編寫響應這些事件的代碼,保存數據。優點:不用事先調入整個文檔,占用資源少;SAX解析器代碼比DOM解析器代碼小,適于Applet,下載。缺點:不是持久的;事件過后,若沒保存數據,那么數據就丟了;無狀態性;從事件中只能得到文本,但不知該文本屬于哪個元素;使用場合:Applet;只需XML文檔的少量內容,很少回頭訪問;機器內存少;

    Java代碼

    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 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) {?? System.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());?? } catch (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;?? public void startDocument() throws SAXException {?? System.out.println("文檔開始打印了");?? }?? public void endDocument() throws SAXException {?? System.out.println("文檔打印結束了");?? }?? public void startElement(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;?? }?? }?? public 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 length)?? 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 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) { System.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()); } catch (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; public void startDocument() throws SAXException { System.out.println("文檔開始打印了"); } public void endDocument() throws SAXException { System.out.println("文檔打印結束了"); } public void startElement(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; } } public 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 length) throws SAXException { System.out.println(new String(ch, start, length)); } }

    3.DOM4J生成和解析XML文檔

    DOM4J 是一個非常非常優秀的Java XML API,具有性能優異、功能強大和極端易用使用的特點,同時它也是一個開放源代碼的軟件。如今你可以看到越來越多的 Java 軟件都在使用 DOM4J 來讀寫 XML,特別值得一提的是連 Sun 的 JAXM 也在用 DOM4J。

    Java代碼

    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.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) {?? Document 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");?? 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());?? }?? }?? 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();?? 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的編碼量,出現了JDOM;優點:20-80原則,極大減少了代碼量。使用場合:要實現的功能簡單,如解析、創建等,但在底層,JDOM還是使用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 createXml(String fileName) {?? Document document;?? Element? root;?? root=new Element("employees");?? document=new Document(root);?? Element employee=new Element("employee");?? root.addContent(employee);?? Element name=new Element("name");?? name.setText("ddvip");?? employee.addContent(name);?? Element sex=new Element("sex");?? sex.setText("m");?? employee.addContent(sex);?? Element age=new Element("age");?? age.setText("23");?? employee.addContent(age);?? XMLOutputter XMLOut = new XMLOutputter();?? try {?? XMLOut.output(document, new FileOutputStream(fileName));?? } catch (FileNotFoundException e) {?? e.printStackTrace();?? } catch (IOException e) {?? e.printStackTrace();?? }?? }?? public void parserXml(String fileName) {?? SAXBuilder builder=new SAXBuilder(false);??? try {?? Document document=builder.build(fileName);?? Element employees=document.getRootElement();??? List employeeList=employees.getChildren("employee");?? for(int i=0;i<EMPLOYEELIST.SIZE();I++){ Element employee=(Element)employeeList.get(i);?? List employeeInfo=employee.getChildren();?? for(int j=0;j<EMPLOYEEINFO.SIZE();J++){ System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());?? }?? }?? } catch (JDOMException e) {?? e.printStackTrace();?? } catch (IOException e) {?? e.printStackTrace();?? }??? }?? }??

    【編輯推薦】

  • XML新手入門 創建構造良好的XML
  • 實現XML和Web服務時要避免的三種常見錯誤
  • 數據庫中的pureXML優點介紹
  • ?

    總結

    以上是生活随笔為你收集整理的Java解析XML汇总(DOM/SAX/JDOM/DOM4j/XPath)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

    主站蜘蛛池模板: 成人免费一级 | 日韩少妇内射免费播放18禁裸乳 | 亚洲a在线观看 | 精品久久久噜噜噜久久久 | 中文字幕+乱码+中文字幕明步 | 伊人国产在线观看 | 天天干天天操天天舔 | 日韩欧美综合视频 | 51精品国产 | 久久新网址 | 欧美日韩一级大片 | 欧美日韩看片 | 国产免费激情 | 国产成人无码精品久久久性色 | 欧美精品国产一区二区 | 无码人妻少妇色欲av一区二区 | 中国一级特黄视频 | av大片在线看 | 免费av导航 | 色综合婷婷 | 97超碰免费在线观看 | 在线视频亚洲欧美 | 日本黄色录相 | 91n在线观看 | 日韩中文在线播放 | 怡红院国产 | 成人免费一区 | 亚洲成年人免费观看 | 无码成人精品区一级毛片 | 色婷婷一区二区三区四区 | 日本无遮羞调教打屁股网站 | 夜色一区二区三区 | 日韩播放| 人妻视频一区二区 | 亚洲欧美另类一区 | 日本一本在线视频 | wwwwxxxx国产| 中文字幕啪啪 | 三上悠亚ssⅰn939无码播放 | 中文字幕一区二区在线观看 | 久久精品久 | 经典三级久久 | 欧美寡妇性猛交ⅹxxx | 欧美日韩精品中文字幕 | 日韩免费小视频 | 欧美丰满美乳xxⅹ高潮www | 黄色片视频网站 | 日韩视频免费在线 | 国产精品社区 | 菊肠扩张playh | 日韩精品视频免费看 | 欧洲视频一区 | 福利视频在线播放 | 色成人综合 | 亚洲人天堂 | 亚洲乱亚洲 | 免费观看国产视频 | xxxxwww一片 | 国产精品麻豆视频 | 亚洲第一免费网站 | 三上悠亚在线观看一区二区 | 日本爽爽爽爽爽爽在线观看免 | 黄色免费av| av中文字幕网站 | jzzijzzij亚洲成熟少妇 | 国产二区精品视频 | 亚洲欧美综合另类 | 玖玖爱在线精品视频 | 九九九九久久久久 | 色哟哟av| 免费裸体视频网站 | 亚洲国产精品自拍视频 | 国产91精品一区二区 | 无码人妻丰满熟妇区bbbbxxxx | 久久久久久久久久福利 | 又黄又骚又爽 | 熟妇人妻系列aⅴ无码专区友真希 | 欧美精品中文 | 欧美三级 欧美一级 | 久久片| 综合久久久久久久久久久 | 欧美放荡办公室videos4k | 日韩精品一二三区 | 大地资源中文在线观看免费版 | 亚洲一本在线观看 | 日本视频黄色 | 国产欧美视频在线 | 爱爱视频一区二区 | 久久日本精品字幕区二区 | 一本大道久久a久久综合婷婷 | 国产高清在线免费 | 成人精品动漫 | 精品偷拍一区 | 成人第四色| 自拍中文字幕 | 国产男女猛烈无遮挡a片漫画 | 亚洲国产中文字幕在线观看 | 紧身裙女教师三上悠亚红杏 | 国产精品国产三级国产专播精品人 |