java解析XML的四种方式及比较

本文深入介绍了XML解析技术,包括DOM、SAX和DOM4J等主流解析方式的特点、应用场景及其实现方法。通过实例展示了如何使用Java进行XML文档的生成与解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XML现在已经成为一种通用的数据交换格式,它的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的方便。对于XML本身的语法知识与技术细节,需要阅读相关的技术文献,这里面包括的内容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations),

XML在不同的语言里解析方式都是一样的,只不过实现的语法不同而已。基本的解析方式有两种,一种叫SAX,另一种叫DOM。SAX是基于事件流的解析,DOM是基于XML文档树结构的解析。假设我们XML的内容和结构如下:


  1. viewplaincopytoclipboardprint?
  2. <?xmlversion=”1.0″encoding=”UTF-8″?><employees>
  3. <employee>
  4. <name>ddviplinux</name>
  5. <sex>m</sex>
  6. <age>30</age>
  7. </employee>
  8. </employees>
  9. <?xmlversion=”1.0″encoding=”UTF-8″?><employees>
  10. <employee>
  11. <name>ddviplinux</name>
  12. <sex>m</sex>
  13. <age>30</age>
  14. </employee>
  15. </employees>

本文使用JAVA语言来实现DOM与SAX的XML文档生成与解析。

首先定义一个操作XML文档的接口XmlDocument 它定义了XML文档的建立与解析的接口。


  1. viewplaincopytoclipboardprint?
  2. packagecom.alisoft.facepay.framework.bean;
  3. /**
  4. *
  5. *@authorhongliang.dinghl
  6. *定义XML文档建立与解析的接口
  7. */
  8. publicinterfaceXmlDocument{
  9. /**
  10. *建立XML文档
  11. *@paramfileName文件全路径名称
  12. */
  13. publicvoidcreateXml(StringfileName);
  14. /**
  15. *解析XML文档
  16. *@paramfileName文件全路径名称
  17. */
  18. 18.publicvoidparserXml(StringfileName);
  19. 19.}
  20. 20.packagecom.alisoft.facepay.framework.bean;
  21. 21./**
  22. 22.*
  23. 23.*@authorhongliang.dinghl
  24. *定义XML文档建立与解析的接口
  25. */
  26. publicinterfaceXmlDocument{
  27. /**
  28. *建立XML文档
  29. *@paramfileName文件全路径名称
  30. */
  31. publicvoidcreateXml(StringfileName);
  32. /**
  33. *解析XML文档
  34. *@paramfileName文件全路径名称
  35. */
  36. publicvoidparserXml(StringfileName);
  37. }
  38. 1. DOM生成和解析XML文档
  39. 为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。

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

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

      
          
      1. viewplaincopytoclipboardprint?
      2. packagecom.alisoft.facepay.framework.bean;
      3. importjava.io.FileInputStream;
      4. importjava.io.FileNotFoundException;
      5. importjava.io.IOException;
      6. importjava.io.InputStream;
      7. importjavax.xml.parsers.ParserConfigurationException;
      8. importjavax.xml.parsers.SAXParser;
      9. importjavax.xml.parsers.SAXParserFactory;
      10. importorg.xml.sax.Attributes;
      11. importorg.xml.sax.SAXException;
      12. importorg.xml.sax.helpers.DefaultHandler;
      13. /**
      14. *@authorhongliang.dinghl
      15. *SAX文档解析
      16. */
      17. publicclassSaxDemoimplementsXmlDocument{
      18. publicvoidcreateXml(StringfileName){
      19. System.out.println(“<<”+filename+“>>”);
      20. }
      21. publicvoidparserXml(StringfileName){
      22. SAXParserFactorysaxfac=SAXParserFactory.newInstance();
      23. try{
      24. SAXParsersaxparser=saxfac.newSAXParser();
      25. InputStreamis=newFileInputStream(fileName);
      26. saxparser.parse(is,newMySAXHandler());
      27. }catch(ParserConfigurationExceptione){
      28. e.printStackTrace();
      29. }catch(SAXExceptione){
      30. e.printStackTrace();
      31. }catch(FileNotFoundExceptione){
      32. e.printStackTrace();
      33. }catch(IOExceptione){
      34. e.printStackTrace();
      35. }
      36. }
      37. }
      38. classMySAXHandlerextendsDefaultHandler{
      39. booleanhasAttribute=false;
      40. Attributesattributes=null;
      41. publicvoidstartDocument()throwsSAXException{
      42. System.out.println(“文档开始打印了“);
      43. }
      44. publicvoidendDocument()throwsSAXException{
      45. System.out.println(“文档打印结束了“);
      46. }
      47. publicvoidstartElement(Stringuri,StringlocalName,StringqName,
      48. Attributesattributes)throwsSAXException{
      49. if(qName.equals(“employees”)){
      50. return;
      51. }
      52. if(qName.equals(“employee”)){
      53. System.out.println(qName);
      54. }
      55. if(attributes.getLength()>0){
      56. this.attributes=attributes;
      57. this.hasAttribute=true;
      58. }
      59. }
      60. publicvoidendElement(Stringuri,StringlocalName,StringqName)
      61. throwsSAXException{
      62. if(hasAttribute&&(attributes!=null)){
      63. for(inti=0;i<attributes.getLength();i++){
      64. System.out.println(attributes.getQName(0)
      65. +attributes.getValue(0));
      66. }
      67. }
      68. }
      69. publicvoidcharacters(char[]ch,intstart,intlength)
      70. throwsSAXException{
      71. System.out.println(newString(ch,start,length));
      72. }
      73. }

      3. DOM4J生成和解析XML文档

      DOM4J 是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。简单易用,采用Java集合框架,并完全支持DOM、SAX和JAXP【优点】①大量使用了Java集合类,方便Java开发人员,同时提供一些提高性能的替代方法。②支持XPath。③有很好的性能。【缺点】①大量使用了接口,API较为复杂。

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

      为减少DOM、SAX的编码量,出现了JDOM;优点:20-80原则,极大减少了代码量。使用场合:要实现的功能简单,如解析、创建等,但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。【优点】①使用具体类而不是接口,简化了DOM的API。②大量使用了Java集合类,方便了Java开发人员。【缺点】①没有较好的灵活性。②性能较差。

      
           
      1. viewplaincopytoclipboardprint?
      2. packagecom.alisoft.facepay.framework.bean;
      3. importjava.io.FileNotFoundException;
      4. importjava.io.FileOutputStream;
      5. importjava.io.IOException;
      6. importjava.util.List;
      7. importorg.jdom.Document;
      8. importorg.jdom.Element;
      9. importorg.jdom.JDOMException;
      10. importorg.jdom.input.SAXBuilder;
      11. importorg.jdom.output.XMLOutputter;
      12. /**
      13. *@authorhongliang.dinghl
      14. *JDOM生成与解析XML文档
      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;i<employeeList.size();i++){
      49. Elementemployee=(Element)employeeList.get(i);
      50. ListemployeeInfo=employee.getChildren();
      51. for(intj=0;j<employeeInfo.size();j++){
      52. System.out.println(((Element)employeeInfo.get(j)).getName()+“:”+
      53. ((Element)employeeInfo.get(j)).getValue());
      54. }
      55. }
      56. }catch(JDOMExceptione){
      57. e.printStackTrace();
      58. }catch(IOExceptione){
      59. e.printStackTrace();
      60. }
      61. }
      62. }

    相关文章推荐:
  40. http://wenda.so.com/q/1381541049066825
  41. http://developer.51cto.com/art/201106/270685_3.htm
  42. http://bbs.youkuaiyun.com/topics/290027113
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值