[转帖] 详解Java解析XML的四种方法_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 4832 | 回复: 0   主题: [转帖] 详解Java解析XML的四种方法        下一篇 
shixisheng
注册用户
等级:上尉
经验:646
发帖:52
精华:0
注册:2013-5-27
状态:离线
发送短消息息给shixisheng 加好友    发送短消息息给shixisheng 发消息
发表于: IP:您无权察看 2013-6-3 14:36:15 | [全部帖] [楼主帖] 楼主

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. <?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>
  9. 复制代码


复制代码


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

  1. package com.alisoft.facepay.framework.bean; 
  2. /** 
  3. * 定义XML文档建立与解析的接口 
  4. */ 
  5. public interface XmlDocument { 
  6.       
  7.       /** 
  8.       
  9.       * 建立XML文档 
  10.       
  11.       * @param fileName 文件全路径名称 
  12.       
  13.       */ 
  14.       
  15.       public void createXml(String fileName); 
  16.       
  17.       /** 
  18.       
  19.       * 解析XML文档 
  20.       
  21.       * @param fileName 文件全路径名称 
  22.       
  23.       */ 
  24.       
  25.       public void parserXml(String fileName); 
  26.       
  27. 复制代码


复制代码
1. DOM生成和解析XML文档

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

  1. package com.alisoft.facepay.framework.bean; 
  2. import java.io.FileInputStream; 
  3. import java.io.FileNotFoundException; 
  4. import java.io.FileOutputStream; 
  5. import java.io.IOException; 
  6. import java.io.InputStream; 
  7. import java.io.PrintWriter; 
  8. import javax.xml.parsers.DocumentBuilder; 
  9. import javax.xml.parsers.DocumentBuilderFactory; 
  10. import javax.xml.parsers.ParserConfigurationException; 
  11. import javax.xml.transform.OutputKeys; 
  12. import javax.xml.transform.Transformer; 
  13. import javax.xml.transform.TransformerConfigurationException; 
  14. import javax.xml.transform.TransformerException; 
  15. import javax.xml.transform.TransformerFactory; 
  16. import javax.xml.transform.dom.DOMSource; 
  17. import javax.xml.transform.stream.StreamResult; 
  18. import org.w3c.dom.Document; 
  19. import org.w3c.dom.Element; 
  20. import org.w3c.dom.Node; 
  21. import org.w3c.dom.NodeList; 
  22. import org.xml.sax.SAXException; 
  23. /** 
  24. * DOM生成与解析XML文档 
  25. */ 
  26. public class DomDemo implements XmlDocument { 
  27.       
  28.       private Document document; 
  29.       
  30.       private String fileName; 
  31.       
  32.       public void init() { 
  33.             
  34.             try { 
  35.                   
  36.                   DocumentBuilderFactory factory = DocumentBuilderFactory 
  37.                   
  38.                   .newInstance(); 
  39.                   
  40.                   DocumentBuilder builder = factory.newDocumentBuilder(); 
  41.                   
  42.                   this.document = builder.newDocument(); 
  43.                   
  44.             } catch (ParserConfigurationException e) { 
  45.                   
  46.                   System.out.println(e.getMessage()); 
  47.                   
  48.             } 
  49.             
  50.       } 
  51.       
  52.       public void createXml(String fileName) { 
  53.             
  54.             Element root = this.document.createElement("employees"); 
  55.             
  56.             this.document.appendChild(root); 
  57.             
  58.             Element employee = this.document.createElement("employee"); 
  59.             
  60.             Element name = this.document.createElement("name"); 
  61.             
  62.             name.appendChild(this.document.createTextNode("丁宏亮")); 
  63.             
  64.             employee.appendChild(name); 
  65.             
  66.             Element sex = this.document.createElement("sex"); 
  67.             
  68.             sex.appendChild(this.document.createTextNode("m")); 
  69.             
  70.             employee.appendChild(sex); 
  71.             
  72.             Element age = this.document.createElement("age"); 
  73.             
  74.             age.appendChild(this.document.createTextNode("30")); 
  75.             
  76.             employee.appendChild(age); 
  77.             
  78.             root.appendChild(employee); 
  79.             
  80.             TransformerFactory tf = TransformerFactory.newInstance(); 
  81.             
  82.             try { 
  83.                   
  84.                   Transformer transformer = tf.newTransformer(); 
  85.                   
  86.                   DOMSource source = new DOMSource(document); 
  87.                   
  88.                   transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312"); 
  89.                   
  90.                   transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
  91.                   
  92.                   PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); 
  93.                   
  94.                   StreamResult result = new StreamResult(pw); 
  95.                   
  96.                   transformer.transform(source, result); 
  97.                   
  98.                   System.out.println("生成XML文件成功!"); 
  99.                   
  100.             } catch (TransformerConfigurationException e) { 
  101.                   
  102.                   System.out.println(e.getMessage()); 
  103.                   
  104.             } catch (IllegalArgumentException e) { 
  105.                   
  106.                   System.out.println(e.getMessage()); 
  107.                   
  108.             } catch (FileNotFoundException e) { 
  109.                   
  110.                   System.out.println(e.getMessage()); 
  111.                   
  112.             } catch (TransformerException e) { 
  113.                   
  114.                   System.out.println(e.getMessage()); 
  115.                   
  116.             } 
  117.             
  118.       } 
  119.       
  120.       public void parserXml(String fileName) { 
  121.             
  122.             try { 
  123.                   
  124.                   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  125.                   
  126.                   DocumentBuilder db = dbf.newDocumentBuilder(); 
  127.                   
  128.                   Document document = db.parse(fileName); 
  129.                   
  130.                   NodeList employees = document.getChildNodes(); 
  131.                   
  132.                   for (int i = 0; i < employees.getLength(); i++) { 
  133.                         
  134.                         Node employee = employees.item(i); 
  135.                         
  136.                         NodeList employeeInfo = employee.getChildNodes(); 
  137.                         
  138.                         for (int j = 0; j < employeeInfo.getLength(); j++) { 
  139.                               
  140.                               Node node = employeeInfo.item(j); 
  141.                               
  142.                               NodeList employeeMeta = node.getChildNodes(); 
  143.                               
  144.                               for (int k = 0; k < employeeMeta.getLength(); k++) { 
  145.                                     
  146.                                     System.out.println(employeeMeta.item(k).getNodeName() 
  147.                                     
  148.                                     + ":" + employeeMeta.item(k).getTextContent()); 
  149.                                     
  150.                               } 
  151.                               
  152.                         } 
  153.                         
  154.                   } 
  155.                   
  156.                   System.out.println("解析完毕"); 
  157.                   
  158.             } catch (FileNotFoundException e) { 
  159.                   
  160.                   System.out.println(e.getMessage()); 
  161.                   
  162.             } catch (ParserConfigurationException e) { 
  163.                   
  164.                   System.out.println(e.getMessage()); 
  165.                   
  166.             } catch (SAXException e) { 
  167.                   
  168.                   System.out.println(e.getMessage()); 
  169.                   
  170.             } catch (IOException e) { 
  171.                   
  172.                   System.out.println(e.getMessage()); 
  173.                   
  174.             } 
  175.             
  176.       } 
  177.       
  178. }
  179. 复制代码


复制���码
2. SAX生成和解析XML文档

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

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;
/**  

*   

* 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;
/**

*

* 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));
      }
}


复制代码
[/code] 3. DOM4J生成和解析XML文档

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

  1. package com.alisoft.facepay.framework.bean; 
  2. import java.io.File; 
  3. import java.io.FileWriter; 
  4. import java.io.IOException; 
  5. import java.io.Writer; 
  6. import java.util.Iterator; 
  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. * Dom4j 生成XML文档与解析XML文档 
  15. */ 
  16. public class Dom4jDemo implements XmlDocument { 
  17.       
  18.       
  19.       
  20.       public void createXml(String fileName) { 
  21.             
  22.             Document document = DocumentHelper.createDocument(); 
  23.             
  24.             Element employees=document.addElement("employees"); 
  25.             
  26.             Element employee=employees.addElement("employee"); 
  27.             
  28.             Element name= employee.addElement("name"); 
  29.             
  30.             name.setText("ddvip"); 
  31.             
  32.             Element sex=employee.addElement("sex"); 
  33.             
  34.             sex.setText("m"); 
  35.             
  36.             Element age=employee.addElement("age"); 
  37.             
  38.             age.setText("29"); 
  39.             
  40.             try { 
  41.                   
  42.                   Writer fileWriter=new FileWriter(fileName); 
  43.                   
  44.                   XMLWriter xmlWriter=new XMLWriter(fileWriter); 
  45.                   
  46.                   xmlWriter.write(document); 
  47.                   
  48.                   xmlWriter.close(); 
  49.                   
  50.             } catch (IOException e) { 
  51.                   
  52.                   
  53.                   
  54.                   System.out.println(e.getMessage()); 
  55.                   
  56.             }
  57.             
  58.       } 
  59.       
  60.       
  61.       
  62.       
  63.       
  64.       public void parserXml(String fileName) { 
  65.             
  66.             File inputXml=new File(fileName); 
  67.             
  68.             SAXReader saxReader = new SAXReader(); 
  69.             
  70.             try { 
  71.                   
  72.                   Document document = saxReader.read(inputXml); 
  73.                   
  74.                   Element employees=document.getRootElement(); 
  75.                   
  76.                   for(Iterator i = employees.elementIterator(); i.hasNext();){ 
  77.                         
  78.                         Element employee = (Element) i.next(); 
  79.                         
  80.                         for(Iterator j = employee.elementIterator(); j.hasNext();){ 
  81.                               
  82.                               Element node=(Element) j.next(); 
  83.                               
  84.                               System.out.println(node.getName()+":"+node.getText()); 
  85.                               
  86.                         } 
  87.                         
  88.                         
  89.                         
  90.                   } 
  91.                   
  92.             } catch (DocumentException e) { 
  93.                   
  94.                   System.out.println(e.getMessage()); 
  95.                   
  96.             } 
  97.             
  98.             System.out.println("dom4j parserXml"); 
  99.             
  100.       } 
  101.       
  102. }
  103. 复制代码


复制代码
4. JDOM生成和解析XML

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

  1. package com.alisoft.facepay.framework.bean; 
  2. import java.io.FileNotFoundException; 
  3. import java.io.FileOutputStream; 
  4. import java.io.IOException; 
  5. import java.util.List; 
  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. * JDOM 生成与解析XML文档 
  13. */ 
  14. public class JDomDemo implements XmlDocument { 
  15.       
  16.       
  17.       
  18.       public void createXml(String fileName) { 
  19.             
  20.             Document document; 
  21.             
  22.             Element root; 
  23.             
  24.             root=new Element("employees"); 
  25.             
  26.             document=new Document(root); 
  27.             
  28.             Element employee=new Element("employee"); 
  29.             
  30.             root.addContent(employee); 
  31.             
  32.             Element name=new Element("name"); 
  33.             
  34.             name.setText("ddvip"); 
  35.             
  36.             employee.addContent(name); 
  37.             
  38.             Element sex=new Element("sex"); 
  39.             
  40.             sex.setText("m"); 
  41.             
  42.             employee.addContent(sex); 
  43.             
  44.             Element age=new Element("age"); 
  45.             
  46.             age.setText("23"); 
  47.             
  48.             employee.addContent(age); 
  49.             
  50.             XMLOutputter XMLOut = new XMLOutputter(); 
  51.             
  52.             try { 
  53.                   
  54.                   XMLOut.output(document, new FileOutputStream(fileName)); 
  55.                   
  56.             } catch (FileNotFoundException e) { 
  57.                   
  58.                   e.printStackTrace(); 
  59.                   
  60.             } catch (IOException e) { 
  61.                   
  62.                   e.printStackTrace(); 
  63.                   
  64.             } 
  65.             
  66.       } 
  67.       
  68.       
  69.       
  70.       public void parserXml(String fileName) { 
  71.             
  72.             SAXBuilder builder=new SAXBuilder(false); 
  73.             
  74.             try { 
  75.                   
  76.                   Document document=builder.build(fileName); 
  77.                   
  78.                   Element employees=document.getRootElement(); 
  79.                   
  80.                   List employeeList=employees.getChildren("employee"); 
  81.                   
  82.                   for(int i=0;i
  83.                   
  84.                   Element employee=(Element)employeeList.get(i); 
  85.                   
  86.                   List employeeInfo=employee.getChildren(); 
  87.                   
  88.                   for(int j=0;j
  89.                   
  90.                   System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue()); 
  91.                   
  92.             } 
  93.             
  94.       } 
  95.       
  96. } catch (JDOMException e) { 
  97.       
  98.       e.printStackTrace(); 
  99.       
  100. } catch (IOException e) { 
  101.       
  102.       e.printStackTrace(); 
  103.       
  104. }




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论