java解析xml
java解析xml文件有四种方式:
1.DOM.
DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准,是以树型结构来表示XML内容.
优点:将整个XML文档一次加载到内存,节点与节点关系也能体现,因此定位节点非常方便,修改文档效率高,且可读可写。
缺点:正是因为一次加载到内存,所以消耗内存,对大文件解析将很吃力。
2.SAX.
采用事件处理机制,一次从头读到尾,不会将整个文件一次加载到内存中,而是读取一部分,解析一部分,占用的内存少。
既然采用事件处理机制,也就回调模式,开发者继承一个SAX解析处理类,然后重写一些方法,当解析XML文档时,发现特定的标签,触发一系列的事件,调用重写方法来处理标签。
优点:处理大型文件效率更高。
确定:只读不写,只能从头读到尾,不能反复操作,实现比较复杂。
3.JDOM.
是Java特定文档模型,把文档的不同内容封装成不同的Java类。
大多数是实现类,极少数是接口,简化了API,限制了灵活性。
大量使用了Java集合框架。
4.DOM4j
大量使用接口,灵活性高,实现更复杂。
大量使用Java中的集合框架。
支持XPath,支持XML Schema,支持XML XSLT。
性能最好。
下面分别用这四中方式解析xml文档.
- <?xml version="1.0" encoding="UTF-8"?>
- <people>
- <person>
- <name>乔峰</name>
- <famous>降龙十八掌</famous>
- </person>
- <person>
- <name>段誉</name>
- <famous>六脉神剑</famous>
- </person>
- <person>
- <name>虚竹</name>
- <famous>天山折梅手</famous>
- </person>
- </people>
<?xml version="1.0" encoding="UTF-8"?> <people> <person> <name>乔峰</name> <famous>降龙十八掌</famous> </person> <person> <name>段誉</name> <famous>六脉神剑</famous> </person> <person> <name>虚竹</name> <famous>天山折梅手</famous> </person> </people>
1.Dom
- package com.xml;
- import java.io.File;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import org.w3c.dom.Document;
- import org.w3c.dom.NodeList;
- public class XmlDom {
- public static void main(String[] args) {
- try {
- File f = new File("src/com/xml/person.xml");
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(f);
- NodeList nl = doc.getElementsByTagName("person");
- for (int i = 0; i < nl.getLength(); i++) {
- System.out.println("人物:" + doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
- System.out.println("绝技:" + doc.getElementsByTagName("famous").item(i).getFirstChild().getNodeValue());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
package com.xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class XmlDom { public static void main(String[] args) { try { File f = new File("src/com/xml/person.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); NodeList nl = doc.getElementsByTagName("person"); for (int i = 0; i < nl.getLength(); i++) { System.out.println("人物:" + doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue()); System.out.println("绝技:" + doc.getElementsByTagName("famous").item(i).getFirstChild().getNodeValue()); } } catch (Exception e) { e.printStackTrace(); } } }
输出结果为:
人物:乔峰
绝技:降龙十八掌
人物:段誉
绝技:六脉神剑
人物:虚竹
绝技:天山折梅手
2.Sax.
- package com.xml;
- import javax.xml.parsers.SAXParser;
- import javax.xml.parsers.SAXParserFactory;
- import org.xml.sax.Attributes;
- import org.xml.sax.InputSource;
- import org.xml.sax.SAXException;
- import org.xml.sax.helpers.DefaultHandler;
- public class XmlSax extends DefaultHandler {
- @SuppressWarnings("unchecked")
- java.util.Stack tags = new java.util.Stack();
- public XmlSax() {
- super();
- }
- public static void main(String[] args) {
- try {
- SAXParserFactory spf = SAXParserFactory.newInstance();
- SAXParser sp = spf.newSAXParser();
- XmlSax xs = new XmlSax();
- sp.parse(new InputSource("src/com/xml/person.xml"), xs);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Override
- public void characters(char[] ch, int start, int length) throws SAXException {
- String tag = (String) tags.peek();
- if (tag.equals("name")) {
- System.out.println("人物:" + new String(ch, start, length));
- }
- if (tag.equals("famous")) {
- System.out.println("绝技:" + new String(ch, start, length));
- }
- }
- @SuppressWarnings("unchecked")
- @Override
- public void startElement(String uri, String localName, String qName, Attributes attrs) {
- tags.push(qName);
- }
- @Override
- public void endElement(String uri, String localName, String qName) {
- }
- }
package com.xml; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XmlSax extends DefaultHandler { @SuppressWarnings("unchecked") java.util.Stack tags = new java.util.Stack(); public XmlSax() { super(); } public static void main(String[] args) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XmlSax xs = new XmlSax(); sp.parse(new InputSource("src/com/xml/person.xml"), xs); } catch (Exception e) { e.printStackTrace(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { String tag = (String) tags.peek(); if (tag.equals("name")) { System.out.println("人物:" + new String(ch, start, length)); } if (tag.equals("famous")) { System.out.println("绝技:" + new String(ch, start, length)); } } @SuppressWarnings("unchecked") @Override public void startElement(String uri, String localName, String qName, Attributes attrs) { tags.push(qName); } @Override public void endElement(String uri, String localName, String qName) { } }
输出结果与上面一样.值得注意的是,如果没有startElement方法,则会出现EmptyStackException异常.
3.JDom
- package com.xml;
- import java.io.File;
- import java.util.List;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.input.SAXBuilder;
- public class XmlJDom {
- @SuppressWarnings("unchecked")
- public static void main(String[] args) {
- try {
- File f = new File("src/com/xml/person.xml");
- SAXBuilder sb = new SAXBuilder();
- Document doc = sb.build(f);
- Element root = doc.getRootElement();
- List ac = root.getChildren();
- for (int i = 0; i < ac.size(); i++) {
- System.out.println("人物:" + ((Element) ac.get(i)).getChild("name").getText());
- System.out.println("绝技:" + ((Element) ac.get(i)).getChild("famous").getText());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
package com.xml; import java.io.File; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; public class XmlJDom { @SuppressWarnings("unchecked") public static void main(String[] args) { try { File f = new File("src/com/xml/person.xml"); SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(f); Element root = doc.getRootElement(); List ac = root.getChildren(); for (int i = 0; i < ac.size(); i++) { System.out.println("人物:" + ((Element) ac.get(i)).getChild("name").getText()); System.out.println("绝技:" + ((Element) ac.get(i)).getChild("famous").getText()); } } catch (Exception e) { e.printStackTrace(); } } }
JDom需要引入jdom.jar包.同样,dom4j需要引入dom4j.jar包.
4.Dom4j
- package com.xml;
- import java.io.File;
- import java.util.Iterator;
- import org.dom4j.Document;
- import org.dom4j.Element;
- import org.dom4j.io.SAXReader;
- public class XmlDom4j {
- @SuppressWarnings("unchecked")
- public static void main(String[] args) {
- try {
- File f = new File("src/com/xml/person.xml");
- SAXReader sr = new SAXReader();
- Document doc = sr.read(f);
- Element root = doc.getRootElement();
- Element el;
- for (Iterator i = root.elementIterator("person"); i.hasNext();) {
- el = (Element) i.next();
- System.out.println("人物:" + el.elementText("name"));
- System.out.println("绝技:" + el.elementText("famous"));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }