解析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的内容和结构如下:

  1. <?xmlversion="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文档的建立与解析的接口。

  1. /**
  2. *
  3. *@authorhongliang.dinghl
  4. *定义XML文档建立与解析的接口
  5. */
  6. publicinterfaceXmlDocument{
  7. /**
  8. *建立XML文档
  9. *@paramfileName文件全路径名称
  10. */
  11. publicvoidcreateXml(StringfileName);
  12. /**
  13. *解析XML文档
  14. *@paramfileName文件全路径名称
  15. */
  16. publicvoidparserXml(StringfileName);
  17. }


1.DOM生成和解析XML文档

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


  1. importjava.io.FileInputStream;
  2. importjava.io.FileNotFoundException;
  3. importjava.io.FileOutputStream;
  4. importjava.io.IOException;
  5. importjava.io.InputStream;
  6. importjava.io.PrintWriter;
  7. importjavax.xml.parsers.DocumentBuilder;
  8. importjavax.xml.parsers.DocumentBuilderFactory;
  9. importjavax.xml.parsers.ParserConfigurationException;
  10. importjavax.xml.transform.OutputKeys;
  11. importjavax.xml.transform.Transformer;
  12. importjavax.xml.transform.TransformerConfigurationException;
  13. importjavax.xml.transform.TransformerException;
  14. importjavax.xml.transform.TransformerFactory;
  15. importjavax.xml.transform.dom.DOMSource;
  16. importjavax.xml.transform.stream.StreamResult;
  17. importorg.w3c.dom.Document;
  18. importorg.w3c.dom.Element;
  19. importorg.w3c.dom.Node;
  20. importorg.w3c.dom.NodeList;
  21. importorg.xml.sax.SAXException;
  22. /**
  23. *
  24. *@authorhongliang.dinghl
  25. *DOM生成与解析XML文档
  26. */
  27. publicclassDomDemoimplementsXmlDocument{
  28. privateDocumentdocument;
  29. privateStringfileName;
  30. publicvoidinit(){
  31. try{
  32. DocumentBuilderFactoryfactory=DocumentBuilderFactory
  33. .newInstance();
  34. DocumentBuilderbuilder=factory.newDocumentBuilder();
  35. this.document=builder.newDocument();
  36. }catch(ParserConfigurationExceptione){
  37. System.out.println(e.getMessage());
  38. }
  39. }
  40. publicvoidcreateXml(StringfileName){
  41. Elementroot=this.document.createElement("employees");
  42. this.document.appendChild(root);
  43. Elementemployee=this.document.createElement("employee");
  44. Elementname=this.document.createElement("name");
  45. name.appendChild(this.document.createTextNode("丁宏亮"));
  46. employee.appendChild(name);
  47. Elementsex=this.document.createElement("sex");
  48. sex.appendChild(this.document.createTextNode("m"));
  49. employee.appendChild(sex);
  50. Elementage=this.document.createElement("age");
  51. age.appendChild(this.document.createTextNode("30"));
  52. employee.appendChild(age);
  53. root.appendChild(employee);
  54. TransformerFactorytf=TransformerFactory.newInstance();
  55. try{
  56. Transformertransformer=tf.newTransformer();
  57. DOMSourcesource=newDOMSource(document);
  58. transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
  59. transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  60. PrintWriterpw=newPrintWriter(newFileOutputStream(fileName));
  61. StreamResultresult=newStreamResult(pw);
  62. transformer.transform(source,result);
  63. System.out.println("生成XML文件成功!");
  64. }catch(TransformerConfigurationExceptione){
  65. System.out.println(e.getMessage());
  66. }catch(IllegalArgumentExceptione){
  67. System.out.println(e.getMessage());
  68. }catch(FileNotFoundExceptione){
  69. System.out.println(e.getMessage());
  70. }catch(TransformerExceptione){
  71. System.out.println(e.getMessage());
  72. }
  73. }
  74. publicvoidparserXml(StringfileName){
  75. try{
  76. DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
  77. DocumentBuilderdb=dbf.newDocumentBuilder();
  78. Documentdocument=db.parse(fileName);
  79. NodeListemployees=document.getChildNodes();
  80. for(inti=0;i<employees.getLength();i++){
  81. Nodeemployee=employees.item(i);
  82. NodeListemployeeInfo=employee.getChildNodes();
  83. for(intj=0;j<employeeInfo.getLength();j++){
  84. Nodenode=employeeInfo.item(j);
  85. NodeListemployeeMeta=node.getChildNodes();
  86. for(intk=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(FileNotFoundExceptione){
  94. System.out.println(e.getMessage());
  95. }catch(ParserConfigurationExceptione){
  96. System.out.println(e.getMessage());
  97. }catch(SAXExceptione){
  98. System.out.println(e.getMessage());
  99. }catch(IOExceptione){
  100. System.out.println(e.getMessage());
  101. }
  102. }
  103. }


2.SAX生成和解析XML文档

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

  1. importjava.io.FileInputStream;
  2. importjava.io.FileNotFoundException;
  3. importjava.io.IOException;
  4. importjava.io.InputStream;
  5. importjavax.xml.parsers.ParserConfigurationException;
  6. importjavax.xml.parsers.SAXParser;
  7. importjavax.xml.parsers.SAXParserFactory;
  8. importorg.xml.sax.Attributes;
  9. importorg.xml.sax.SAXException;
  10. importorg.xml.sax.helpers.DefaultHandler;
  11. /**
  12. *
  13. *@authorhongliang.dinghl
  14. *SAX文档解析
  15. */
  16. publicclassSaxDemoimplementsXmlDocument{
  17. publicvoidcreateXml(StringfileName){
  18. System.out.println("<<"+filename+">>");
  19. }
  20. publicvoidparserXml(StringfileName){
  21. SAXParserFactorysaxfac=SAXParserFactory.newInstance();
  22. try{
  23. SAXParsersaxparser=saxfac.newSAXParser();
  24. InputStreamis=newFileInputStream(fileName);
  25. saxparser.parse(is,newMySAXHandler());
  26. }catch(ParserConfigurationExceptione){
  27. e.printStackTrace();
  28. }catch(SAXExceptione){
  29. e.printStackTrace();
  30. }catch(FileNotFoundExceptione){
  31. e.printStackTrace();
  32. }catch(IOExceptione){
  33. e.printStackTrace();
  34. }
  35. }
  36. }
  37. classMySAXHandlerextendsDefaultHandler{
  38. booleanhasAttribute=false;
  39. Attributesattributes=null;
  40. publicvoidstartDocument()throwsSAXException{
  41. System.out.println("文档开始打印了");
  42. }
  43. publicvoidendDocument()throwsSAXException{
  44. System.out.println("文档打印结束了");
  45. }
  46. publicvoidstartElement(Stringuri,StringlocalName,StringqName,
  47. Attributesattributes)throwsSAXException{
  48. if(qName.equals("employees")){
  49. return;
  50. }
  51. if(qName.equals("employee")){
  52. System.out.println(qName);
  53. }
  54. if(attributes.getLength()>0){
  55. this.attributes=attributes;
  56. this.hasAttribute=true;
  57. }
  58. }
  59. publicvoidendElement(Stringuri,StringqName)
  60. throwsSAXException{
  61. if(hasAttribute&&(attributes!=null)){
  62. for(inti=0;i<attributes.getLength();i++){
  63. System.out.println(attributes.getQName(0)
  64. +attributes.getValue(0));
  65. }
  66. }
  67. }
  68. publicvoidcharacters(char[]ch,intstart,intlength)
  69. throwsSAXException{
  70. System.out.println(newString(ch,start,length));
  71. }
  72. }
  73. packagecom.alisoft.facepay.framework.bean;
  74. importjava.io.FileInputStream;
  75. importjava.io.FileNotFoundException;
  76. importjava.io.IOException;
  77. importjava.io.InputStream;
  78. importjavax.xml.parsers.ParserConfigurationException;
  79. importjavax.xml.parsers.SAXParser;
  80. importjavax.xml.parsers.SAXParserFactory;
  81. importorg.xml.sax.Attributes;
  82. importorg.xml.sax.SAXException;
  83. importorg.xml.sax.helpers.DefaultHandler;
  84. /**
  85. *
  86. *@authorhongliang.dinghl
  87. *SAX文档解析
  88. */
  89. publicclassSaxDemoimplementsXmlDocument{
  90. publicvoidcreateXml(StringfileName){
  91. System.out.println("<<"+filename+">>");
  92. }
  93. publicvoidparserXml(StringfileName){
  94. SAXParserFactorysaxfac=SAXParserFactory.newInstance();
  95. try{
  96. SAXParsersaxparser=saxfac.newSAXParser();
  97. InputStreamis=newFileInputStream(fileName);
  98. saxparser.parse(is,newMySAXHandler());
  99. }catch(ParserConfigurationExceptione){
  100. e.printStackTrace();
  101. }catch(SAXExceptione){
  102. e.printStackTrace();
  103. }catch(FileNotFoundExceptione){
  104. e.printStackTrace();
  105. }catch(IOExceptione){
  106. e.printStackTrace();
  107. }
  108. }
  109. }
  110. classMySAXHandlerextendsDefaultHandler{
  111. booleanhasAttribute=false;
  112. Attributesattributes=null;
  113. publicvoidstartDocument()throwsSAXException{
  114. System.out.println("文档开始打印了");
  115. }
  116. publicvoidendDocument()throwsSAXException{
  117. System.out.println("文档打印结束了");
  118. }
  119. publicvoidstartElement(Stringuri,
  120. Attributesattributes)throwsSAXException{
  121. if(qName.equals("employees")){
  122. return;
  123. }
  124. if(qName.equals("employee")){
  125. System.out.println(qName);
  126. }
  127. if(attributes.getLength()>0){
  128. this.attributes=attributes;
  129. this.hasAttribute=true;
  130. }
  131. }
  132. publicvoidendElement(Stringuri,StringqName)
  133. throwsSAXException{
  134. if(hasAttribute&&(attributes!=null)){
  135. for(inti=0;i<attributes.getLength();i++){
  136. System.out.println(attributes.getQName(0)
  137. +attributes.getValue(0));
  138. }
  139. }
  140. }
  141. publicvoidcharacters(char[]ch,intlength)
  142. throwsSAXException{
  143. System.out.println(newString(ch,length));
  144. }
  145. }


3.DOM4J生成和解析XML文档

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


  1. importjava.io.File;
  2. importjava.io.FileWriter;
  3. importjava.io.IOException;
  4. importjava.io.Writer;
  5. importjava.util.Iterator;
  6. importorg.dom4j.Document;
  7. importorg.dom4j.DocumentException;
  8. importorg.dom4j.DocumentHelper;
  9. importorg.dom4j.Element;
  10. importorg.dom4j.io.SAXReader;
  11. importorg.dom4j.io.XMLWriter;
  12. /**
  13. *
  14. *@authorhongliang.dinghl
  15. *Dom4j生成XML文档与解析XML文档
  16. */
  17. publicclassDom4jDemoimplementsXmlDocument{
  18. publicvoidcreateXml(StringfileName){
  19. Documentdocument=DocumentHelper.createDocument();
  20. Elementemployees=document.addElement("employees");
  21. Elementemployee=employees.addElement("employee");
  22. Elementname=employee.addElement("name");
  23. name.setText("ddvip");
  24. Elementsex=employee.addElement("sex");
  25. sex.setText("m");
  26. Elementage=employee.addElement("age");
  27. age.setText("29");
  28. try{
  29. WriterfileWriter=newFileWriter(fileName);
  30. XMLWriterxmlWriter=newXMLWriter(fileWriter);
  31. xmlWriter.write(document);
  32. xmlWriter.close();
  33. }catch(IOExceptione){
  34. System.out.println(e.getMessage());
  35. }
  36. }
  37. publicvoidparserXml(StringfileName){
  38. FileinputXml=newFile(fileName);
  39. SAXReadersaxReader=newSAXReader();
  40. try{
  41. Documentdocument=saxReader.read(inputXml);
  42. Elementemployees=document.getRootElement();
  43. for(Iteratori=employees.elementIterator();i.hasNext();){
  44. Elementemployee=(Element)i.next();
  45. for(Iteratorj=employee.elementIterator();j.hasNext();){
  46. Elementnode=(Element)j.next();
  47. System.out.println(node.getName()+":"+node.getText());
  48. }
  49. }
  50. }catch(DocumentExceptione){
  51. System.out.println(e.getMessage());
  52. }
  53. System.out.println("dom4jparserXml");
  54. }
  55. }

4.JDOM生成和解析XML

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

  1. importjava.io.FileNotFoundException;
  2. importjava.io.FileOutputStream;
  3. importjava.io.IOException;
  4. importjava.util.List;
  5. importorg.jdom.Document;
  6. importorg.jdom.Element;
  7. importorg.jdom.JDOMException;
  8. importorg.jdom.input.SAXBuilder;
  9. importorg.jdom.output.XMLOutputter;
  10. /**
  11. *
  12. *@authorhongliang.dinghl
  13. *JDOM生成与解析XML文档
  14. *
  15. */
  16. publicclassJDomDemoimplementsXmlDocument{
  17. publicvoidcreateXml(StringfileName){
  18. Documentdocument;
  19. Elementroot;
  20. root=newElement("employees");
  21. document=newDocument(root);
  22. Elementemployee=newElement("employee");
  23. root.addContent(employee);
  24. Elementname=newElement("name");
  25. name.setText("ddvip");
  26. employee.addContent(name);
  27. Elementsex=newElement("sex");
  28. sex.setText("m");
  29. employee.addContent(sex);
  30. Elementage=newElement("age");
  31. age.setText("23");
  32. employee.addContent(age);
  33. XMLOutputterXMLOut=newXMLOutputter();
  34. try{
  35. XMLOut.output(document,newFileOutputStream(fileName));
  36. }catch(FileNotFoundExceptione){
  37. e.printStackTrace();
  38. }catch(IOExceptione){
  39. e.printStackTrace();
  40. }
  41. }
  42. publicvoidparserXml(StringfileName){
  43. SAXBuilderbuilder=newSAXBuilder(false);
  44. try{
  45. Documentdocument=builder.build(fileName);
  46. Elementemployees=document.getRootElement();
  47. ListemployeeList=employees.getChildren("employee");
  48. for(inti=0;iElementemployee=(Element)employeeList.get(i);
  49. ListemployeeInfo=employee.getChildren();
  50. for(intj=0;jSystem.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());
  51. }
  52. }
  53. }catch(JDOMExceptione){
  54. e.printStackTrace();
  55. }catch(IOExceptione){
  56. e.printStackTrace();
  57. }
  58. }
  59. }

相关文章

引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满足人的生产生活需要而产生的。具体...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
http://blog.jobbole.com/79252/ 引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满...
(点击上方公众号,可快速关注) 公众号:smart_android 作者:耿广龙|loonggg 点击“阅读原文”,可查看...
一、xml与xslt 相信所有人对xml都不陌生,其被广泛的应用于数据数据传输、保存与序列化中,是一种极为强...