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分析器還是有很廣泛的使用價值的。
- 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
- {
- // step 1: 獲得dom解析器工廠(工作的作用是用於創建具體的解析器)
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- // System.out.println("class name: " + dbf.getClass().getName());
- // step 2:獲得具體的dom解析器
- DocumentBuilder db = dbf.newDocumentBuilder();
- // System.out.println("class name: " + db.getClass().getName());
- // step3: 解析一個xml文檔,獲得Document對象(根結點)
- 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("--------------------------------------");
- }
- }
- }
- 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;
- /**
- * 使用遞歸解析給定的任意一個xml文檔並且將其內容輸出到命令行上
- * @author zhanglong
- *
- */
- 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);
- //element元素的所有屬性所構成的NamedNodeMap對象,需要對其進行判斷
- 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接口也被稱作事件驅動接口。
- 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
- {
- //step1: 獲得SAX解析器工廠實例
- SAXParserFactory factory = SAXParserFactory.newInstance();
- //step2: 獲得SAX解析器實例
- SAXParser parser = factory.newSAXParser();
- //step3: 開始進行解析
- 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");
- }
- }
- 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
- 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(" ");
- // format.setEncoding("gbk");
- XMLOutputter out = new XMLOutputter(format);
- out.output(document, new FileWriter("jdom.xml"));
- }
- }
JDOM解析xml
- 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
- 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
- {
- // 創建文檔並設置文檔的根元素節點 :第一種方式
- // Document document = DocumentHelper.createDocument();
- //
- // Element root = DocumentHelper.createElement("student");
- //
- // document.setRootElement(root);
- // 創建文檔並設置文檔的根元素節點 :第二種方式
- 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();
- }
- }
- 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();
- //將JAXP的Document轉換爲dom4j的Document
- Document d = domReader.read(document);
- Element rootElement = d.getRootElement();
- System.out.println(rootElement.getName());
- }
- }
- 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"));
- }
- }
附:
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"?>
|
本文使用JAVA語言來實現DOM與SAX的XML文檔生成與解析。
首先定義一個操作XML文檔的接口XmlDocument 它定義了XML文檔的建立與解析的接口。
package com.alisoft.facepay.framework.bean;
|
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文檔。
<span style="background-color: rgb(255, 255, 255);">package com.alisoft.facepay.framework.bean; <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />import java.io.FileNotFoundException; <br style="clear: both; width: 0px; height: 0px;" />import java.io.FileOutputStream; <br style="clear: both; width: 0px; height: 0px;" />import java.io.IOException; <br style="clear: both; width: 0px; height: 0px;" />import java.util.List; <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />import org.jdom.Document; <br style="clear: both; width: 0px; height: 0px;" />import org.jdom.Element; <br style="clear: both; width: 0px; height: 0px;" />import org.jdom.JDOMException; <br style="clear: both; width: 0px; height: 0px;" />import org.jdom.input.SAXBuilder; <br style="clear: both; width: 0px; height: 0px;" />import org.jdom.output.XMLOutputter; <br style="clear: both; width: 0px; height: 0px;" />/** <br style="clear: both; width: 0px; height: 0px;" />* <br style="clear: both; width: 0px; height: 0px;" />* @author hongliang.dinghl <br style="clear: both; width: 0px; height: 0px;" />* JDOM 生成與解析XML文檔 <br style="clear: both; width: 0px; height: 0px;" />* <br style="clear: both; width: 0px; height: 0px;" />*/ <br style="clear: both; width: 0px; height: 0px;" />public class JDomDemo implements XmlDocument { <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />public void createXml(String fileName) { <br style="clear: both; width: 0px; height: 0px;" />Document document; <br style="clear: both; width: 0px; height: 0px;" />Element root; <br style="clear: both; width: 0px; height: 0px;" />root=new Element("employees"); <br style="clear: both; width: 0px; height: 0px;" />document=new Document(root); <br style="clear: both; width: 0px; height: 0px;" />Element employee=new Element("employee"); <br style="clear: both; width: 0px; height: 0px;" />root.addContent(employee); <br style="clear: both; width: 0px; height: 0px;" />Element name=new Element("name"); <br style="clear: both; width: 0px; height: 0px;" />name.setText("ddvip"); <br style="clear: both; width: 0px; height: 0px;" />employee.addContent(name); <br style="clear: both; width: 0px; height: 0px;" />Element sex=new Element("sex"); <br style="clear: both; width: 0px; height: 0px;" />sex.setText("m"); <br style="clear: both; width: 0px; height: 0px;" />employee.addContent(sex); <br style="clear: both; width: 0px; height: 0px;" />Element age=new Element("age"); <br style="clear: both; width: 0px; height: 0px;" />age.setText("23"); <br style="clear: both; width: 0px; height: 0px;" />employee.addContent(age); <br style="clear: both; width: 0px; height: 0px;" />XMLOutputter XMLOut = new XMLOutputter(); <br style="clear: both; width: 0px; height: 0px;" />try { <br style="clear: both; width: 0px; height: 0px;" />XMLOut.output(document, new FileOutputStream(fileName)); <br style="clear: both; width: 0px; height: 0px;" />} catch (FileNotFoundException e) { <br style="clear: both; width: 0px; height: 0px;" />e.printStackTrace(); <br style="clear: both; width: 0px; height: 0px;" />} catch (IOException e) { <br style="clear: both; width: 0px; height: 0px;" />e.printStackTrace(); <br style="clear: both; width: 0px; height: 0px;" />} <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />} <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />public void parserXml(String fileName) { <br style="clear: both; width: 0px; height: 0px;" />SAXBuilder builder=new SAXBuilder(false); <br style="clear: both; width: 0px; height: 0px;" />try { <br style="clear: both; width: 0px; height: 0px;" />Document document=builder.build(fileName); <br style="clear: both; width: 0px; height: 0px;" />Element employees=document.getRootElement(); <br style="clear: both; width: 0px; height: 0px;" />List employeeList=employees.getChildren("employee"); <br style="clear: both; width: 0px; height: 0px;" />for(int i=0;i<employeelist.size();i++){ Element employee=(Element)employeeList.get(i); <br style="clear: both; width: 0px; height: 0px;" />List employeeInfo=employee.getChildren(); <br style="clear: both; width: 0px; height: 0px;" />for(int j=0;j<employeeinfo.size();j++){ System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue()); <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />} <br style="clear: both; width: 0px; height: 0px;" />} <br style="clear: both; width: 0px; height: 0px;" />} catch (JDOMException e) { <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />e.printStackTrace(); <br style="clear: both; width: 0px; height: 0px;" />} catch (IOException e) { <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />e.printStackTrace(); <br style="clear: both; width: 0px; height: 0px;" />} <br style="clear: both; width: 0px; height: 0px;" /><br style="clear: both; width: 0px; height: 0px;" />} <br style="clear: both; width: 0px; height: 0px;" />} </span>