解析XNL文件

来源:互联网 发布:驾照报考软件 编辑:程序博客网 时间:2024/06/02 01:51
  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的内容和结构如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <employees>   
  3. <employee>   
  4. <name>ddviplinux</name>   
  5. <sex>m</sex>   
  6. <age>30</age>   
  7. </employee>   
  8. </employees>  
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <employees>   
  3. <employee>   
  4. <name>ddviplinux</name>   
  5. <sex>m</sex>   
  6. <age>30</age>   
  7. </employee>   
  8. </employees>  

本文使用JAVA语言来实现DOM与SAX的XML文档生成与解析。 
首先定义一个操作XML文档的接口XmlDocument 它定义了XML文档的建立与解析的接口。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /**  
  2.  
  3. * @author hongliang.dinghl  
  4. * 定义XML文档建立与解析的接口  
  5. */   
  6. public interface XmlDocument {   
  7. /**  
  8. * 建立XML文档  
  9. * @param fileName 文件全路径名称  
  10. */   
  11. public void createXml(String fileName);   
  12. /**  
  13. * 解析XML文档  
  14. * @param fileName 文件全路径名称  
  15. */   
  16. public void parserXml(String fileName);   
  17. }   
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /**  
  2.  
  3. * @author hongliang.dinghl  
  4. * 定义XML文档建立与解析的接口  
  5. */   
  6. public interface XmlDocument {   
  7. /**  
  8. * 建立XML文档  
  9. * @param fileName 文件全路径名称  
  10. */   
  11. public void createXml(String fileName);   
  12. /**  
  13. * 解析XML文档  
  14. * @param fileName 文件全路径名称  
  15. */   
  16. public void parserXml(String fileName);   
  17. }   


1.DOM生成和解析XML文档

为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.io.FileInputStream;   
  2. import java.io.FileNotFoundException;   
  3. import java.io.FileOutputStream;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.io.PrintWriter;   
  7. import javax.xml.parsers.DocumentBuilder;   
  8. import javax.xml.parsers.DocumentBuilderFactory;   
  9. import javax.xml.parsers.ParserConfigurationException;   
  10. import javax.xml.transform.OutputKeys;   
  11. import javax.xml.transform.Transformer;   
  12. import javax.xml.transform.TransformerConfigurationException;   
  13. import javax.xml.transform.TransformerException;   
  14. import javax.xml.transform.TransformerFactory;   
  15. import javax.xml.transform.dom.DOMSource;   
  16. import javax.xml.transform.stream.StreamResult;   
  17. import org.w3c.dom.Document;   
  18. import org.w3c.dom.Element;   
  19. import org.w3c.dom.Node;   
  20. import org.w3c.dom.NodeList;   
  21. import org.xml.sax.SAXException;   
  22. /**  
  23.  
  24. * @author hongliang.dinghl  
  25. * DOM生成与解析XML文档  
  26. */   
  27. public class DomDemo implements XmlDocument {   
  28. private Document document;   
  29. private String fileName;   
  30. public void init() {   
  31. try {   
  32. DocumentBuilderFactory factory = DocumentBuilderFactory   
  33. .newInstance();   
  34. DocumentBuilder builder = factory.newDocumentBuilder();   
  35. this.document = builder.newDocument();   
  36. catch (ParserConfigurationException e) {   
  37. System.out.println(e.getMessage());   
  38. }   
  39. }   
  40. public void createXml(String fileName) {   
  41. Element root = this.document.createElement("employees");   
  42. this.document.appendChild(root);   
  43. Element employee = this.document.createElement("employee");   
  44. Element name = this.document.createElement("name");   
  45. name.appendChild(this.document.createTextNode("丁宏亮"));   
  46. employee.appendChild(name);   
  47. Element sex = this.document.createElement("sex");   
  48. sex.appendChild(this.document.createTextNode("m"));   
  49. employee.appendChild(sex);   
  50. Element age = this.document.createElement("age");   
  51. age.appendChild(this.document.createTextNode("30"));   
  52. employee.appendChild(age);   
  53. root.appendChild(employee);   
  54. TransformerFactory tf = TransformerFactory.newInstance();   
  55. try {   
  56. Transformer transformer = tf.newTransformer();   
  57. DOMSource source = new DOMSource(document);   
  58. transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");   
  59. transformer.setOutputProperty(OutputKeys.INDENT, "yes");   
  60. PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));   
  61. StreamResult result = new StreamResult(pw);   
  62. transformer.transform(source, result);   
  63. System.out.println("生成XML文件成功!");   
  64. catch (TransformerConfigurationException e) {   
  65. System.out.println(e.getMessage());   
  66. catch (IllegalArgumentException e) {   
  67. System.out.println(e.getMessage());   
  68. catch (FileNotFoundException e) {   
  69. System.out.println(e.getMessage());   
  70. catch (TransformerException e) {   
  71. System.out.println(e.getMessage());   
  72. }   
  73. }   
  74. public void parserXml(String fileName) {   
  75. try {   
  76. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
  77. DocumentBuilder db = dbf.newDocumentBuilder();   
  78. Document document = db.parse(fileName);   
  79. NodeList employees = document.getChildNodes();   
  80. for (int i = 0; i < employees.getLength(); i++) {   
  81. Node employee = employees.item(i);   
  82. NodeList employeeInfo = employee.getChildNodes();   
  83. for (int j = 0; j < employeeInfo.getLength(); j++) {   
  84. Node node = employeeInfo.item(j);   
  85. NodeList employeeMeta = node.getChildNodes();   
  86. for (int k = 0; k < employeeMeta.getLength(); k++) {   
  87. System.out.println(employeeMeta.item(k).getNodeName()   
  88. ":" + employeeMeta.item(k).getTextContent());   
  89. }   
  90. }   
  91. }   
  92. System.out.println("解析完毕");   
  93. catch (FileNotFoundException e) {   
  94. System.out.println(e.getMessage());   
  95. catch (ParserConfigurationException e) {   
  96. System.out.println(e.getMessage());   
  97. catch (SAXException e) {   
  98. System.out.println(e.getMessage());   
  99. catch (IOException e) {   
  100. System.out.println(e.getMessage());   
  101. }   
  102. }   
  103. }   
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.FileInputStream;   
  2. import java.io.FileNotFoundException;   
  3. import java.io.FileOutputStream;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.io.PrintWriter;   
  7. import javax.xml.parsers.DocumentBuilder;   
  8. import javax.xml.parsers.DocumentBuilderFactory;   
  9. import javax.xml.parsers.ParserConfigurationException;   
  10. import javax.xml.transform.OutputKeys;   
  11. import javax.xml.transform.Transformer;   
  12. import javax.xml.transform.TransformerConfigurationException;   
  13. import javax.xml.transform.TransformerException;   
  14. import javax.xml.transform.TransformerFactory;   
  15. import javax.xml.transform.dom.DOMSource;   
  16. import javax.xml.transform.stream.StreamResult;   
  17. import org.w3c.dom.Document;   
  18. import org.w3c.dom.Element;   
  19. import org.w3c.dom.Node;   
  20. import org.w3c.dom.NodeList;   
  21. import org.xml.sax.SAXException;   
  22. /**  
  23.  
  24. * @author hongliang.dinghl  
  25. * DOM生成与解析XML文档  
  26. */   
  27. public class DomDemo implements XmlDocument {   
  28. private Document document;   
  29. private String fileName;   
  30. public void init() {   
  31. try {   
  32. DocumentBuilderFactory factory = DocumentBuilderFactory   
  33. .newInstance();   
  34. DocumentBuilder builder = factory.newDocumentBuilder();   
  35. this.document = builder.newDocument();   
  36. catch (ParserConfigurationException e) {   
  37. System.out.println(e.getMessage());   
  38. }   
  39. }   
  40. public void createXml(String fileName) {   
  41. Element root = this.document.createElement("employees");   
  42. this.document.appendChild(root);   
  43. Element employee = this.document.createElement("employee");   
  44. Element name = this.document.createElement("name");   
  45. name.appendChild(this.document.createTextNode("丁宏亮"));   
  46. employee.appendChild(name);   
  47. Element sex = this.document.createElement("sex");   
  48. sex.appendChild(this.document.createTextNode("m"));   
  49. employee.appendChild(sex);   
  50. Element age = this.document.createElement("age");   
  51. age.appendChild(this.document.createTextNode("30"));   
  52. employee.appendChild(age);   
  53. root.appendChild(employee);   
  54. TransformerFactory tf = TransformerFactory.newInstance();   
  55. try {   
  56. Transformer transformer = tf.newTransformer();   
  57. DOMSource source = new DOMSource(document);   
  58. transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");   
  59. transformer.setOutputProperty(OutputKeys.INDENT, "yes");   
  60. PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));   
  61. StreamResult result = new StreamResult(pw);   
  62. transformer.transform(source, result);   
  63. System.out.println("生成XML文件成功!");   
  64. catch (TransformerConfigurationException e) {   
  65. System.out.println(e.getMessage());   
  66. catch (IllegalArgumentException e) {   
  67. System.out.println(e.getMessage());   
  68. catch (FileNotFoundException e) {   
  69. System.out.println(e.getMessage());   
  70. catch (TransformerException e) {   
  71. System.out.println(e.getMessage());   
  72. }   
  73. }   
  74. public void parserXml(String fileName) {   
  75. try {   
  76. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
  77. DocumentBuilder db = dbf.newDocumentBuilder();   
  78. Document document = db.parse(fileName);   
  79. NodeList employees = document.getChildNodes();   
  80. for (int i = 0; i < employees.getLength(); i++) {   
  81. Node employee = employees.item(i);   
  82. NodeList employeeInfo = employee.getChildNodes();   
  83. for (int j = 0; j < employeeInfo.getLength(); j++) {   
  84. Node node = employeeInfo.item(j);   
  85. NodeList employeeMeta = node.getChildNodes();   
  86. for (int k = 0; k < employeeMeta.getLength(); k++) {   
  87. System.out.println(employeeMeta.item(k).getNodeName()   
  88. ":" + employeeMeta.item(k).getTextContent());   
  89. }   
  90. }   
  91. }   
  92. System.out.println("解析完毕");   
  93. catch (FileNotFoundException e) {   
  94. System.out.println(e.getMessage());   
  95. catch (ParserConfigurationException e) {   
  96. System.out.println(e.getMessage());   
  97. catch (SAXException e) {   
  98. System.out.println(e.getMessage());   
  99. catch (IOException e) {   
  100. System.out.println(e.getMessage());   
  101. }   
  102. }   
  103. }   


2.SAX生成和解析XML文档

为解决DOM的问题,出现了SAX。SAX ,事件驱动。当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.io.FileInputStream;     
  2. import java.io.FileNotFoundException;     
  3. import java.io.IOException;     
  4. import java.io.InputStream;     
  5.   
  6. import javax.xml.parsers.ParserConfigurationException;     
  7. import javax.xml.parsers.SAXParser;     
  8. import javax.xml.parsers.SAXParserFactory;     
  9.   
  10. import org.xml.sax.Attributes;     
  11. import org.xml.sax.SAXException;     
  12. import org.xml.sax.helpers.DefaultHandler;     
  13. /**   
  14. *    
  15. * @author hongliang.dinghl   
  16. * SAX文档解析   
  17. */    
  18. public class SaxDemo implements XmlDocument {     
  19.   
  20. public void createXml(String fileName) {     
  21. System.out.println("<<"+filename+">>");     
  22. }     
  23.   
  24. public void parserXml(String fileName) {     
  25. SAXParserFactory saxfac = SAXParserFactory.newInstance();     
  26.   
  27. try {     
  28.   
  29. SAXParser saxparser = saxfac.newSAXParser();     
  30.   
  31. InputStream is = new FileInputStream(fileName);     
  32.   
  33. saxparser.parse(is, new MySAXHandler());     
  34.   
  35. catch (ParserConfigurationException e) {     
  36.   
  37. e.printStackTrace();     
  38.   
  39. catch (SAXException e) {     
  40.   
  41. e.printStackTrace();     
  42.   
  43. catch (FileNotFoundException e) {     
  44.   
  45. e.printStackTrace();     
  46.   
  47. catch (IOException e) {     
  48.   
  49. e.printStackTrace();     
  50.   
  51. }     
  52.   
  53. }     
  54.   
  55. }     
  56.   
  57. class MySAXHandler extends DefaultHandler {     
  58.   
  59. boolean hasAttribute = false;     
  60.   
  61. Attributes attributes = null;     
  62.   
  63. public void startDocument() throws SAXException {     
  64.   
  65. System.out.println("文档开始打印了");     
  66.   
  67. }     
  68.   
  69. public void endDocument() throws SAXException {     
  70.   
  71. System.out.println("文档打印结束了");     
  72.   
  73. }     
  74.   
  75. public void startElement(String uri, String localName, String qName,     
  76.   
  77. Attributes attributes) throws SAXException {     
  78.   
  79. if (qName.equals("employees")) {     
  80.   
  81. return;     
  82.   
  83. }     
  84.   
  85. if (qName.equals("employee")) {     
  86.   
  87. System.out.println(qName);     
  88.   
  89. }     
  90.   
  91. if (attributes.getLength() > 0) {     
  92.   
  93. this.attributes = attributes;     
  94.   
  95. this.hasAttribute = true;     
  96.   
  97. }     
  98.   
  99. }     
  100.   
  101. public void endElement(String uri, String localName, String qName)     
  102.   
  103. throws SAXException {     
  104.   
  105. if (hasAttribute && (attributes != null)) {     
  106.   
  107. for (int i = 0; i < attributes.getLength(); i++) {     
  108.   
  109. System.out.println(attributes.getQName(0)     
  110. + attributes.getValue(0));     
  111.   
  112. }     
  113.   
  114. }     
  115.   
  116. }     
  117.   
  118. public void characters(char[] ch, int start, int length)     
  119.   
  120. throws SAXException {     
  121.   
  122. System.out.println(new String(ch, start, length));     
  123.   
  124. }     
  125.   
  126. }    
  127. package com.alisoft.facepay.framework.bean;   
  128. import java.io.FileInputStream;   
  129. import java.io.FileNotFoundException;   
  130. import java.io.IOException;   
  131. import java.io.InputStream;   
  132. import javax.xml.parsers.ParserConfigurationException;   
  133. import javax.xml.parsers.SAXParser;   
  134. import javax.xml.parsers.SAXParserFactory;   
  135. import org.xml.sax.Attributes;   
  136. import org.xml.sax.SAXException;   
  137. import org.xml.sax.helpers.DefaultHandler;   
  138. /**  
  139.  
  140. * @author hongliang.dinghl  
  141. * SAX文档解析  
  142. */   
  143. public class SaxDemo implements XmlDocument {   
  144. public void createXml(String fileName) {   
  145. System.out.println("<<"+filename+">>");   
  146. }   
  147. public void parserXml(String fileName) {   
  148. SAXParserFactory saxfac = SAXParserFactory.newInstance();   
  149. try {   
  150. SAXParser saxparser = saxfac.newSAXParser();   
  151. InputStream is = new FileInputStream(fileName);   
  152. saxparser.parse(is, new MySAXHandler());   
  153. catch (ParserConfigurationException e) {   
  154. e.printStackTrace();   
  155. catch (SAXException e) {   
  156. e.printStackTrace();   
  157. catch (FileNotFoundException e) {   
  158. e.printStackTrace();   
  159. catch (IOException e) {   
  160. e.printStackTrace();   
  161. }   
  162. }   
  163. }   
  164. class MySAXHandler extends DefaultHandler {   
  165. boolean hasAttribute = false;   
  166. Attributes attributes = null;   
  167. public void startDocument() throws SAXException {   
  168. System.out.println("文档开始打印了");   
  169. }   
  170. public void endDocument() throws SAXException {   
  171. System.out.println("文档打印结束了");   
  172. }   
  173. public void startElement(String uri, String localName, String qName,   
  174. Attributes attributes) throws SAXException {   
  175. if (qName.equals("employees")) {   
  176. return;   
  177. }   
  178. if (qName.equals("employee")) {   
  179. System.out.println(qName);   
  180. }   
  181. if (attributes.getLength() > 0) {   
  182. this.attributes = attributes;   
  183. this.hasAttribute = true;   
  184. }   
  185. }   
  186. public void endElement(String uri, String localName, String qName)   
  187. throws SAXException {   
  188. if (hasAttribute && (attributes != null)) {   
  189. for (int i = 0; i < attributes.getLength(); i++) {   
  190. System.out.println(attributes.getQName(0)   
  191. + attributes.getValue(0));   
  192. }   
  193. }   
  194. }   
  195. public void characters(char[] ch, int start, int length)   
  196. throws SAXException {   
  197. System.out.println(new String(ch, start, length));   
  198. }   
  199. }   
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.FileInputStream;     
  2. import java.io.FileNotFoundException;     
  3. import java.io.IOException;     
  4. import java.io.InputStream;     
  5.   
  6. import javax.xml.parsers.ParserConfigurationException;     
  7. import javax.xml.parsers.SAXParser;     
  8. import javax.xml.parsers.SAXParserFactory;     
  9.   
  10. import org.xml.sax.Attributes;     
  11. import org.xml.sax.SAXException;     
  12. import org.xml.sax.helpers.DefaultHandler;     
  13. /**   
  14. *    
  15. * @author hongliang.dinghl   
  16. * SAX文档解析   
  17. */    
  18. public class SaxDemo implements XmlDocument {     
  19.   
  20. public void createXml(String fileName) {     
  21. System.out.println("<<"+filename+">>");     
  22. }     
  23.   
  24. public void parserXml(String fileName) {     
  25. SAXParserFactory saxfac = SAXParserFactory.newInstance();     
  26.   
  27. try {     
  28.   
  29. SAXParser saxparser = saxfac.newSAXParser();     
  30.   
  31. InputStream is = new FileInputStream(fileName);     
  32.   
  33. saxparser.parse(is, new MySAXHandler());     
  34.   
  35. catch (ParserConfigurationException e) {     
  36.   
  37. e.printStackTrace();     
  38.   
  39. catch (SAXException e) {     
  40.   
  41. e.printStackTrace();     
  42.   
  43. catch (FileNotFoundException e) {     
  44.   
  45. e.printStackTrace();     
  46.   
  47. catch (IOException e) {     
  48.   
  49. e.printStackTrace();     
  50.   
  51. }     
  52.   
  53. }     
  54.   
  55. }     
  56.   
  57. class MySAXHandler extends DefaultHandler {     
  58.   
  59. boolean hasAttribute = false;     
  60.   
  61. Attributes attributes = null;     
  62.   
  63. public void startDocument() throws SAXException {     
  64.   
  65. System.out.println("文档开始打印了");     
  66.   
  67. }     
  68.   
  69. public void endDocument() throws SAXException {     
  70.   
  71. System.out.println("文档打印结束了");     
  72.   
  73. }     
  74.   
  75. public void startElement(String uri, String localName, String qName,     
  76.   
  77. Attributes attributes) throws SAXException {     
  78.   
  79. if (qName.equals("employees")) {     
  80.   
  81. return;     
  82.   
  83. }     
  84.   
  85. if (qName.equals("employee")) {     
  86.   
  87. System.out.println(qName);     
  88.   
  89. }     
  90.   
  91. if (attributes.getLength() > 0) {     
  92.   
  93. this.attributes = attributes;     
  94.   
  95. this.hasAttribute = true;     
  96.   
  97. }     
  98.   
  99. }     
  100.   
  101. public void endElement(String uri, String localName, String qName)     
  102.   
  103. throws SAXException {     
  104.   
  105. if (hasAttribute && (attributes != null)) {     
  106.   
  107. for (int i = 0; i < attributes.getLength(); i++) {     
  108.   
  109. System.out.println(attributes.getQName(0)     
  110. + attributes.getValue(0));     
  111.   
  112. }     
  113.   
  114. }     
  115.   
  116. }     
  117.   
  118. public void characters(char[] ch, int start, int length)     
  119.   
  120. throws SAXException {     
  121.   
  122. System.out.println(new String(ch, start, length));     
  123.   
  124. }     
  125.   
  126. }    
  127. package com.alisoft.facepay.framework.bean;   
  128. import java.io.FileInputStream;   
  129. import java.io.FileNotFoundException;   
  130. import java.io.IOException;   
  131. import java.io.InputStream;   
  132. import javax.xml.parsers.ParserConfigurationException;   
  133. import javax.xml.parsers.SAXParser;   
  134. import javax.xml.parsers.SAXParserFactory;   
  135. import org.xml.sax.Attributes;   
  136. import org.xml.sax.SAXException;   
  137. import org.xml.sax.helpers.DefaultHandler;   
  138. /**  
  139.  
  140. * @author hongliang.dinghl  
  141. * SAX文档解析  
  142. */   
  143. public class SaxDemo implements XmlDocument {   
  144. public void createXml(String fileName) {   
  145. System.out.println("<<"+filename+">>");   
  146. }   
  147. public void parserXml(String fileName) {   
  148. SAXParserFactory saxfac = SAXParserFactory.newInstance();   
  149. try {   
  150. SAXParser saxparser = saxfac.newSAXParser();   
  151. InputStream is = new FileInputStream(fileName);   
  152. saxparser.parse(is, new MySAXHandler());   
  153. catch (ParserConfigurationException e) {   
  154. e.printStackTrace();   
  155. catch (SAXException e) {   
  156. e.printStackTrace();   
  157. catch (FileNotFoundException e) {   
  158. e.printStackTrace();   
  159. catch (IOException e) {   
  160. e.printStackTrace();   
  161. }   
  162. }   
  163. }   
  164. class MySAXHandler extends DefaultHandler {   
  165. boolean hasAttribute = false;   
  166. Attributes attributes = null;   
  167. public void startDocument() throws SAXException {   
  168. System.out.println("文档开始打印了");   
  169. }   
  170. public void endDocument() throws SAXException {   
  171. System.out.println("文档打印结束了");   
  172. }   
  173. public void startElement(String uri, String localName, String qName,   
  174. Attributes attributes) throws SAXException {   
  175. if (qName.equals("employees")) {   
  176. return;   
  177. }   
  178. if (qName.equals("employee")) {   
  179. System.out.println(qName);   
  180. }   
  181. if (attributes.getLength() > 0) {   
  182. this.attributes = attributes;   
  183. this.hasAttribute = true;   
  184. }   
  185. }   
  186. public void endElement(String uri, String localName, String qName)   
  187. throws SAXException {   
  188. if (hasAttribute && (attributes != null)) {   
  189. for (int i = 0; i < attributes.getLength(); i++) {   
  190. System.out.println(attributes.getQName(0)   
  191. + attributes.getValue(0));   
  192. }   
  193. }   
  194. }   
  195. public void characters(char[] ch, int start, int length)   
  196. throws SAXException {   
  197. System.out.println(new String(ch, start, length));   
  198. }   
  199. }   


3.DOM4J生成和解析XML文档

DOM4J 是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.io.File;     
  2. import java.io.FileWriter;     
  3. import java.io.IOException;     
  4. import java.io.Writer;     
  5. import java.util.Iterator;     
  6.   
  7. import org.dom4j.Document;     
  8. import org.dom4j.DocumentException;     
  9. import org.dom4j.DocumentHelper;     
  10. import org.dom4j.Element;     
  11. import org.dom4j.io.SAXReader;     
  12. import org.dom4j.io.XMLWriter;     
  13. /**   
  14. *    
  15. * @author hongliang.dinghl   
  16. * Dom4j 生成XML文档与解析XML文档   
  17. */    
  18. public class Dom4jDemo implements XmlDocument {     
  19.   
  20. public void createXml(String fileName) {     
  21. Document document = DocumentHelper.createDocument();     
  22. Element employees=document.addElement("employees");     
  23. Element employee=employees.addElement("employee");     
  24. Element name= employee.addElement("name");     
  25. name.setText("ddvip");     
  26. Element sex=employee.addElement("sex");     
  27. sex.setText("m");     
  28. Element age=employee.addElement("age");     
  29. age.setText("29");     
  30. try {     
  31. Writer fileWriter=new FileWriter(fileName);     
  32. XMLWriter xmlWriter=new XMLWriter(fileWriter);     
  33. xmlWriter.write(document);     
  34. xmlWriter.close();     
  35. catch (IOException e) {     
  36.   
  37. System.out.println(e.getMessage());     
  38. }     
  39.   
  40.   
  41. }     
  42.   
  43.   
  44. public void parserXml(String fileName) {     
  45. File inputXml=new File(fileName);     
  46. SAXReader saxReader = new SAXReader();     
  47. try {     
  48. Document document = saxReader.read(inputXml);     
  49. Element employees=document.getRootElement();     
  50. for(Iterator i = employees.elementIterator(); i.hasNext();){     
  51. Element employee = (Element) i.next();     
  52. for(Iterator j = employee.elementIterator(); j.hasNext();){     
  53. Element node=(Element) j.next();     
  54. System.out.println(node.getName()+":"+node.getText());     
  55. }     
  56.   
  57. }     
  58. catch (DocumentException e) {     
  59. System.out.println(e.getMessage());     
  60. }     
  61. System.out.println("dom4j parserXml");     
  62. }     
  63. }     
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.File;     
  2. import java.io.FileWriter;     
  3. import java.io.IOException;     
  4. import java.io.Writer;     
  5. import java.util.Iterator;     
  6.   
  7. import org.dom4j.Document;     
  8. import org.dom4j.DocumentException;     
  9. import org.dom4j.DocumentHelper;     
  10. import org.dom4j.Element;     
  11. import org.dom4j.io.SAXReader;     
  12. import org.dom4j.io.XMLWriter;     
  13. /**   
  14. *    
  15. * @author hongliang.dinghl   
  16. * Dom4j 生成XML文档与解析XML文档   
  17. */    
  18. public class Dom4jDemo implements XmlDocument {     
  19.   
  20. public void createXml(String fileName) {     
  21. Document document = DocumentHelper.createDocument();     
  22. Element employees=document.addElement("employees");     
  23. Element employee=employees.addElement("employee");     
  24. Element name= employee.addElement("name");     
  25. name.setText("ddvip");     
  26. Element sex=employee.addElement("sex");     
  27. sex.setText("m");     
  28. Element age=employee.addElement("age");     
  29. age.setText("29");     
  30. try {     
  31. Writer fileWriter=new FileWriter(fileName);     
  32. XMLWriter xmlWriter=new XMLWriter(fileWriter);     
  33. xmlWriter.write(document);     
  34. xmlWriter.close();     
  35. catch (IOException e) {     
  36.   
  37. System.out.println(e.getMessage());     
  38. }     
  39.   
  40.   
  41. }     
  42.   
  43.   
  44. public void parserXml(String fileName) {     
  45. File inputXml=new File(fileName);     
  46. SAXReader saxReader = new SAXReader();     
  47. try {     
  48. Document document = saxReader.read(inputXml);     
  49. Element employees=document.getRootElement();     
  50. for(Iterator i = employees.elementIterator(); i.hasNext();){     
  51. Element employee = (Element) i.next();     
  52. for(Iterator j = employee.elementIterator(); j.hasNext();){     
  53. Element node=(Element) j.next();     
  54. System.out.println(node.getName()+":"+node.getText());     
  55. }     
  56.   
  57. }     
  58. catch (DocumentException e) {     
  59. System.out.println(e.getMessage());     
  60. }     
  61. System.out.println("dom4j parserXml");     
  62. }     
  63. }     

4.JDOM生成和解析XML  

为减少DOM、SAX的编码量,出现了JDOM;优点:20-80原则,极大减少了代码量。使用场合:要实现的功能简单,如解析、创建等,但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.io.FileNotFoundException;     
  2. import java.io.FileOutputStream;     
  3. import java.io.IOException;     
  4. import java.util.List;     
  5.   
  6. import org.jdom.Document;     
  7. import org.jdom.Element;     
  8. import org.jdom.JDOMException;     
  9. import org.jdom.input.SAXBuilder;     
  10. import org.jdom.output.XMLOutputter;     
  11. /**   
  12. *    
  13. * @author hongliang.dinghl   
  14. * JDOM 生成与解析XML文档   
  15. *    
  16. */    
  17. public class JDomDemo implements XmlDocument {     
  18.   
  19. public void createXml(String fileName) {     
  20. Document document;     
  21. Element  root;     
  22. root=new Element("employees");     
  23. document=new Document(root);     
  24. Element employee=new Element("employee");     
  25. root.addContent(employee);     
  26. Element name=new Element("name");     
  27. name.setText("ddvip");     
  28. employee.addContent(name);     
  29. Element sex=new Element("sex");     
  30. sex.setText("m");     
  31. employee.addContent(sex);     
  32. Element age=new Element("age");     
  33. age.setText("23");     
  34. employee.addContent(age);     
  35. XMLOutputter XMLOut = new XMLOutputter();     
  36. try {     
  37. XMLOut.output(document, new FileOutputStream(fileName));     
  38. catch (FileNotFoundException e) {     
  39. e.printStackTrace();     
  40. catch (IOException e) {     
  41. e.printStackTrace();     
  42. }     
  43.   
  44. }     
  45.   
  46. public void parserXml(String fileName) {     
  47. SAXBuilder builder=new SAXBuilder(false);      
  48. try {     
  49. Document document=builder.build(fileName);     
  50. Element employees=document.getRootElement();      
  51. List employeeList=employees.getChildren("employee");     
  52. for(int i=0;iElement employee=(Element)employeeList.get(i);     
  53. List employeeInfo=employee.getChildren();     
  54. for(int j=0;jSystem.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());     
  55.   
  56. }     
  57. }     
  58. catch (JDOMException e) {     
  59.   
  60. e.printStackTrace();     
  61. catch (IOException e) {     
  62.   
  63. e.printStackTrace();     
  64. }      
  65.   
  66. }     
  67. }     
  68.     
0 0
原创粉丝点击