生活随笔
收集整理的這篇文章主要介紹了
java解析xml的几种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java解析xml的幾種方式 博客分類: XMLJava應用服務器數據結構編程?
第一種:DOM。 DOM的全稱是Document Object Model,也即文檔對象模型。在應用程序中,基于DOM的XML分析器將一個XML文檔轉換成一個對象模型的集合(通常稱DOM樹),應用程序正是通過對這個對象模型的操作,來實現對XML文檔數據的操作。通過DOM接口,應用程序可以在任何時候訪問XML文檔中的任何一部分數據,因此,這種利用DOM接口的機制也被稱作隨機訪問機制。 DOM接口提供了一種通過分層對象模型來訪問XML文檔信息的方式,這些分層對象模型依據XML的文檔結構形成了一棵節點樹。無論XML文檔中所描述的是什么類型的信息,即便是制表數據、項目列表或一個文檔,利用DOM所生成的模型都是節點樹的形式。也就是說,DOM強制使用樹模型來訪問XML文檔中的信息。由于XML本質上就是一種分層結構,所以這種描述方法是相當有效的。 DOM樹所提供的隨機訪問方式給應用程序的開發帶來了很大的靈活性,它可以任意地控制整個XML文檔中的內容。然而,由于DOM分析器把整個XML文檔轉化成DOM樹放在了內存中,因此,當文檔比較大或者結構比較復雜時,對內存的需求就比較高。而且,對于結構復雜的樹的遍歷也是一項耗時的操作。所以,DOM分析器對機器性能的要求比較高,實現效率不十分理想。不過,由于DOM分析器所采用的樹結構的思想與XML文檔的結構相吻合,同時鑒于隨機訪問所帶來的方便,因此,DOM分析器還是有很廣泛的使用價值的。
Java代碼??
import?java.io.File;?? ?? import?javax.xml.parsers.DocumentBuilder;?? import?javax.xml.parsers.DocumentBuilderFactory;?? ?? import?org.w3c.dom.Document;?? import?org.w3c.dom.Element;?? import?org.w3c.dom.NodeList;?? ?? public?class?DomTest1?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ???????? ????????DocumentBuilderFactory?dbf?=?DocumentBuilderFactory.newInstance();?? ?????????? ?????????? ???????? ????????DocumentBuilder?db?=?dbf.newDocumentBuilder();?? ?????????? ?????????? ???????? ????????Document?document?=?db.parse(new?File("candidate.xml"));?? ?????????? ????????NodeList?list?=?document.getElementsByTagName("PERSON");?? ?????????? ????????for(int?i?=?0;?i?<?list.getLength();?i++)?? ????????{?? ????????????Element?element?=?(Element)list.item(i);?? ?????????????? ????????????String?content?=?element.getElementsByTagName("NAME").item(0).getFirstChild().getNodeValue();?? ?????????????? ????????????System.out.println("name:"?+?content);?? ?????????????? ????????????content?=?element.getElementsByTagName("ADDRESS").item(0).getFirstChild().getNodeValue();?? ?????????????? ????????????System.out.println("address:"?+?content);?? ?????????????? ????????????content?=?element.getElementsByTagName("TEL").item(0).getFirstChild().getNodeValue();?? ?????????????? ????????????System.out.println("tel:"?+?content);?? ?????????????? ????????????content?=?element.getElementsByTagName("FAX").item(0).getFirstChild().getNodeValue();?? ?????????????? ????????????System.out.println("fax:"?+?content);?? ?????????????? ????????????content?=?element.getElementsByTagName("EMAIL").item(0).getFirstChild().getNodeValue();?? ?????????????? ????????????System.out.println("email:"?+?content);?? ?????????????? ????????????System.out.println("--------------------------------------");?? ????????}?? ????}?? }?? ?
Java代碼??
import?java.io.File;?? ?? import?javax.xml.parsers.DocumentBuilder;?? import?javax.xml.parsers.DocumentBuilderFactory;?? ?? import?org.w3c.dom.Attr;?? import?org.w3c.dom.Comment;?? import?org.w3c.dom.Document;?? import?org.w3c.dom.Element;?? import?org.w3c.dom.NamedNodeMap;?? import?org.w3c.dom.Node;?? import?org.w3c.dom.NodeList;?? ?? public?class?DomTest3?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ????????DocumentBuilderFactory?dbf?=?DocumentBuilderFactory.newInstance();?? ????????DocumentBuilder?db?=?dbf.newDocumentBuilder();?? ?????????? ????????Document?doc?=?db.parse(new?File("student.xml"));?? ???????? ????????Element?root?=?doc.getDocumentElement();?? ?????????? ????????parseElement(root);?? ????}?? ?????? ????private?static?void?parseElement(Element?element)?? ????{?? ????????String?tagName?=?element.getNodeName();?? ?????????? ????????NodeList?children?=?element.getChildNodes();?? ?????????? ????????System.out.print("<"?+?tagName);?? ?????????? ???????? ????????NamedNodeMap?map?=?element.getAttributes();?? ?????????? ???????? ????????if(null?!=?map)?? ????????{?? ????????????for(int?i?=?0;?i?<?map.getLength();?i++)?? ????????????{?? ???????????????? ????????????????Attr?attr?=?(Attr)map.item(i);?? ?????????????????? ????????????????String?attrName?=?attr.getName();?? ????????????????String?attrValue?=?attr.getValue();?? ?????????????????? ????????????????System.out.print("?"?+?attrName?+?"=\""?+?attrValue?+?"\"");?? ????????????}?? ????????}?? ?????????? ????????System.out.print(">");?? ?????????? ????????for(int?i?=?0;?i?<?children.getLength();?i++)?? ????????{?? ????????????Node?node?=?children.item(i);?? ???????????? ????????????short?nodeType?=?node.getNodeType();?? ?????????????? ????????????if(nodeType?==?Node.ELEMENT_NODE)?? ????????????{?? ???????????????? ????????????????parseElement((Element)node);?? ????????????}?? ????????????else?if(nodeType?==?Node.TEXT_NODE)?? ????????????{?? ???????????????? ????????????????System.out.print(node.getNodeValue());?? ????????????}?? ????????????else?if(nodeType?==?Node.COMMENT_NODE)?? ????????????{?? ????????????????System.out.print("<!--");?? ?????????????????? ????????????????Comment?comment?=?(Comment)node;?? ?????????????????? ???????????????? ????????????????String?data?=?comment.getData();?? ?????????????????? ????????????????System.out.print(data);?? ?????????????????? ????????????????System.out.print("-->");?? ????????????}?? ????????}?? ?????????? ????????System.out.print("</"?+?tagName?+?">");?? ????}?? }?? ?
?
?
sax:SAX的全稱是Simple APIs for XML,也即XML簡單應用程序接口。與DOM不同,SAX提供的訪問模式是一種順序模式,這是一種快速讀寫XML數據的方式。當使用SAX分析器對XML文檔進行分析時,會觸發一系列事件,并激活相應的事件處理函數,應用程序通過這些事件處理函數實現對XML文檔的訪問,因而SAX接口也被稱作事件驅動接口。
?
?
Java代碼??
import?java.io.File;?? ?? 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?SaxTest1?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ???????? ????????SAXParserFactory?factory?=?SAXParserFactory.newInstance();?? ?????????? ???????? ????????SAXParser?parser?=?factory.newSAXParser();?? ?????????? ???????? ????????parser.parse(new?File("student.xml"),?new?MyHandler());?? ?????????? ????}?? }?? ?? class?MyHandler?extends?DefaultHandler?? {?? ????@Override?? ????public?void?startDocument()?throws?SAXException?? ????{?? ????????System.out.println("parse?began");?? ????}?? ?????? ????@Override?? ????public?void?endDocument()?throws?SAXException?? ????{?? ????????System.out.println("parse?finished");?? ????}?? ?????? ????@Override?? ????public?void?startElement(String?uri,?String?localName,?String?qName,?? ????????????Attributes?attributes)?throws?SAXException?? ????{?? ????????System.out.println("start?element");?? ????}?? ?????? ????@Override?? ????public?void?endElement(String?uri,?String?localName,?String?qName)?? ????????????throws?SAXException?? ????{?? ????????System.out.println("finish?element");?? ????}?? }?? ?
?
Java代碼??
import?java.io.File;?? import?java.util.Stack;?? ?? 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?SaxTest2?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ????????SAXParserFactory?factory?=?SAXParserFactory.newInstance();?? ?????????? ????????SAXParser?parser?=?factory.newSAXParser();?? ?????????? ????????parser.parse(new?File("student.xml"),?new?MyHandler2());?? ????}?? }?? ?? class?MyHandler2?extends?DefaultHandler?? {?? ????private?Stack<String>?stack?=?new?Stack<String>();?? ?????? ????private?String?name;?? ?????? ????private?String?gender;?? ?????? ????private?String?age;?? ?????? ????@Override?? ????public?void?startElement(String?uri,?String?localName,?String?qName,?? ????????????Attributes?attributes)?throws?SAXException?? ????{?? ????????stack.push(qName);?? ?????????? ????????for(int?i?=?0;?i?<?attributes.getLength();?i++)?? ????????{?? ????????????String?attrName?=?attributes.getQName(i);?? ????????????String?attrValue?=?attributes.getValue(i);?? ?????????????? ????????????System.out.println(attrName?+?"="?+?attrValue);?? ????????}?? ????}?? ?????? ????@Override?? ????public?void?characters(char[]?ch,?int?start,?int?length)?? ????????????throws?SAXException?? ????{?? ????????String?tag?=?stack.peek();?? ?????????? ????????if("姓名".equals(tag))?? ????????{?? ????????????name?=?new?String(ch,?start,length);?? ????????}?? ????????else?if("性別".equals(tag))?? ????????{?? ????????????gender?=?new?String(ch,?start,?length);?? ????????}?? ????????else?if("年齡".equals(tag))?? ????????{?? ????????????age?=?new?String(ch,?start,?length);?? ????????}?? ????}?? ?????? ????@Override?? ????public?void?endElement(String?uri,?String?localName,?String?qName)?? ????????????throws?SAXException?? ????{?? ????????stack.pop();? ?????????? ????????if("學生".equals(qName))?? ????????{?? ????????????System.out.println("姓名:"?+?name);?? ????????????System.out.println("性別:"?+?gender);?? ????????????System.out.println("年齡:"?+?age);?? ?????????????? ????????????System.out.println();?? ????????}?? ?????????? ????}?? }?? ?
JDOM:
?
JDOM是一個開源項目,它基于樹型結構,利用純JAVA的技術對XML文檔實現解析、生成、序列化以及多種操作。(http://jdom.org)
?JDOM 直接為JAVA編程服務。它利用更為強有力的JAVA語言的諸多特性(方法重載、集合概念等),把SAX和DOM的功能有效地結合起來。
?JDOM是用Java語言讀、寫、操作XML的新API函數。在直接、簡單和高效的前提下,這些API函數被最大限度的優化。
?
?
jdom創建xml
?
Java代碼??
import?java.io.FileWriter;?? ?? import?org.jdom.Attribute;?? import?org.jdom.Comment;?? import?org.jdom.Document;?? import?org.jdom.Element;?? import?org.jdom.output.Format;?? import?org.jdom.output.XMLOutputter;?? ?? public?class?JDomTest1?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ????????Document?document?=?new?Document();?? ?? ????????Element?root?=?new?Element("root");?? ?? ????????document.addContent(root);?? ?? ????????Comment?comment?=?new?Comment("This?is?my?comments");?? ?? ????????root.addContent(comment);?? ?? ????????Element?e?=?new?Element("hello");?? ?? ????????e.setAttribute("sohu",?"www.sohu.com");?? ?? ????????root.addContent(e);?? ?? ????????Element?e2?=?new?Element("world");?? ?? ????????Attribute?attr?=?new?Attribute("test",?"hehe");?? ?? ????????e2.setAttribute(attr);?? ?? ????????e.addContent(e2);?? ?? ????????e2.addContent(new?Element("aaa").setAttribute("a",?"b")?? ????????????????.setAttribute("x",?"y").setAttribute("gg",?"hh").setText("text?content"));?? ?? ?????????? ????????Format?format?=?Format.getPrettyFormat();?? ?????????? ????????format.setIndent("????");?? ?????????? ????????XMLOutputter?out?=?new?XMLOutputter(format);?? ?? ????????out.output(document,?new?FileWriter("jdom.xml"));?? ?????????? ????}?? }?? ?
JDOM解析xml
?
Java代碼??
import?java.io.File;?? import?java.io.FileOutputStream;?? import?java.util.List;?? ?? import?org.jdom.Attribute;?? import?org.jdom.Document;?? import?org.jdom.Element;?? import?org.jdom.input.SAXBuilder;?? import?org.jdom.output.Format;?? import?org.jdom.output.XMLOutputter;?? ?? public?class?JDomTest2?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ????????SAXBuilder?builder?=?new?SAXBuilder();?? ?????????? ????????Document?doc?=?builder.build(new?File("jdom.xml"));?? ?????????? ????????Element?element?=?doc.getRootElement();?? ?????????? ????????System.out.println(element.getName());?? ?????????? ????????Element?hello?=?element.getChild("hello");?? ?????????? ????????System.out.println(hello.getText());?? ?????????? ????????List?list?=?hello.getAttributes();?? ?????????? ????????for(int?i?=?0?;i?<?list.size();?i++)?? ????????{?? ????????????Attribute?attr?=?(Attribute)list.get(i);?? ?????????????? ????????????String?attrName?=?attr.getName();?? ????????????String?attrValue?=?attr.getValue();?? ?????????????? ????????????System.out.println(attrName?+?"="?+?attrValue);?? ????????}?? ?????????? ????????hello.removeChild("world");?? ?????????? ????????XMLOutputter?out?=?new?XMLOutputter(Format.getPrettyFormat().setIndent("????"));?? ?????????? ?????????? ????????out.output(doc,?new?FileOutputStream("jdom2.xml"));??????? ?????????? ????}?? }?? ?
?
Dom4j
?
?
Java代碼??
import?java.io.FileOutputStream;?? import?java.io.FileWriter;?? ?? import?org.dom4j.Document;?? import?org.dom4j.DocumentHelper;?? import?org.dom4j.Element;?? import?org.dom4j.io.OutputFormat;?? import?org.dom4j.io.XMLWriter;?? ?? public?class?Test1?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ???????? ???????? ???????? ???????? ???????? ???????? ?? ???????? ????????Element?root?=?DocumentHelper.createElement("student");?? ????????Document?document?=?DocumentHelper.createDocument(root);?? ?? ????????root.addAttribute("name",?"zhangsan");?? ?? ????????Element?helloElement?=?root.addElement("hello");?? ????????Element?worldElement?=?root.addElement("world");?? ?? ????????helloElement.setText("hello");?? ????????worldElement.setText("world");?? ?? ????????helloElement.addAttribute("age",?"20");?? ?? ????????XMLWriter?xmlWriter?=?new?XMLWriter();?? ????????xmlWriter.write(document);?? ?????????? ????????OutputFormat?format?=?new?OutputFormat("????",?true);?? ?????????? ????????XMLWriter?xmlWriter2?=?new?XMLWriter(new?FileOutputStream("student2.xml"),?format);?? ????????xmlWriter2.write(document);?? ?????????? ????????XMLWriter?xmlWriter3?=?new?XMLWriter(new?FileWriter("student3.xml"),?format);?? ?????????? ????????xmlWriter3.write(document);?? ????????xmlWriter3.close();?? ?? ????}?? }?? ?
?
Java代碼??
import?java.io.File;?? import?java.util.Iterator;?? import?java.util.List;?? ?? import?javax.xml.parsers.DocumentBuilder;?? import?javax.xml.parsers.DocumentBuilderFactory;?? ?? import?org.dom4j.Document;?? import?org.dom4j.Element;?? import?org.dom4j.io.DOMReader;?? import?org.dom4j.io.SAXReader;?? ?? public?class?Test2?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ????????SAXReader?saxReader?=?new?SAXReader();?? ?????????? ????????Document?doc?=?saxReader.read(new?File("student2.xml"));?? ?????????? ????????Element?root?=?doc.getRootElement();?? ?????????? ????????System.out.println("root?element:?"?+?root.getName());?? ?????????? ????????List?childList?=?root.elements();?? ?????????? ????????System.out.println(childList.size());?? ?????????? ????????List?childList2?=?root.elements("hello");?? ?????????? ????????System.out.println(childList2.size());?? ?????????? ????????Element?first?=?root.element("hello");?? ?????????? ????????System.out.println(first.attributeValue("age"));?? ?????????? ????????for(Iterator?iter?=?root.elementIterator();?iter.hasNext();)?? ????????{?? ????????????Element?e?=?(Element)iter.next();?? ?????????????? ????????????System.out.println(e.attributeValue("age"));?? ????????}?? ?????????? ????????System.out.println("---------------------------");?? ?????????? ????????DocumentBuilderFactory?dbf?=?DocumentBuilderFactory.newInstance();?? ????????DocumentBuilder?db?=?dbf.newDocumentBuilder();?? ????????org.w3c.dom.Document?document?=?db.parse(new?File("student2.xml"));?? ?????????? ????????DOMReader?domReader?=?new?DOMReader();?? ?????????? ???????? ????????Document?d?=?domReader.read(document);?? ?????????? ????????Element?rootElement?=?d.getRootElement();?? ?????????? ????????System.out.println(rootElement.getName());?? ?? ????}?? }?? ?
?
Java代碼??
import?java.io.FileWriter;?? ?? import?org.jdom.Attribute;?? import?org.jdom.Document;?? import?org.jdom.Element;?? import?org.jdom.output.Format;?? import?org.jdom.output.XMLOutputter;?? ?? public?class?Test3?? {?? ????public?static?void?main(String[]?args)?throws?Exception?? ????{?? ????????Document?document?=?new?Document();?? ?? ????????Element?root?=?new?Element("聯系人列表").setAttribute(new?Attribute("公司",?? ????????????????"A集團"));?? ?? ????????document.addContent(root);?? ?????????? ????????Element?contactPerson?=?new?Element("聯系人");?? ?????????? ????????root.addContent(contactPerson);?? ?? ????????contactPerson?? ????????????????.addContent(new?Element("姓名").setText("張三"))?? ????????????????.addContent(new?Element("公司").setText("A公司"))?? ????????????????.addContent(new?Element("電話").setText("021-55556666"))?? ????????????????.addContent(?? ????????????????????????new?Element("地址")?? ????????????????????????????????.addContent(new?Element("街道").setText("5街"))?? ????????????????????????????????.addContent(new?Element("城市").setText("上海"))?? ????????????????????????????????.addContent(new?Element("省份").setText("上海市")));?? ?? ????????XMLOutputter?output?=?new?XMLOutputter(Format.getPrettyFormat()?? ????????????????.setIndent("????").setEncoding("gbk"));?? ?? ????????output.output(document,?new?FileWriter("contact.xml"));?? ?? ????}?? }?? ?
分享到:?? 策略模式(stratege)?|?反射-JUnit4的執行的一般流
2011-04-22 07:45 瀏覽 107765 評論(8) 分類:企業架構 相關推薦 評論 8 樓?TomJay?2016-02-24?? ?原諒強迫癥的我,發現了一個錯誤 7 樓?zh554275855?2015-09-01?? 在項目ulimian具體怎么用啊?哥哥 6 樓?麥田的設計者?2014-12-15?? XmlPullParser 呢? 5 樓?wilhard?2014-09-09?? 復習一下,不記筆記真是學一樣丟一樣啊 4 樓?jxlzl1988?2014-03-13?? nice 3 樓?木偶的妖刀?2014-03-01?? nice?? 2 樓?oyxe?2013-10-11?? ?不錯 1 樓?lbl331592517?2013-09-25?? ?good http://inotgaoshou.iteye.com/blog/1012188 http://www.cnblogs.com/mengdd/archive/2013/06/05/3119927.html http://bbs.csdn.net/topics/290027113 http://jingyan.baidu.com/article/84b4f565f3239260f6da320b.html
轉載于:https://www.cnblogs.com/pengmn/p/5250536.html
總結
以上是生活随笔 為你收集整理的java解析xml的几种方式 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。