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

一、XML语言的特点
1、XML独立于任何编程语言,允许人们按接收者容易解析的方式,对复杂数据进行编码。先来看一个简单的XML格式的文件:

[html]view plaincopyprint?

  1. <note>  
  2. <to>George</to>  
  3. <from>John</from>  
  4. <heading>Reminder</heading>  
  5. <body>Don't forget the meeting!</body>  
  6. </note>  


<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>


对于程序员来说,很容易读懂这是什么意思,很明显这是传递给他人的一个便签,如果我们写出下面这样:

 George
John
Reminder
Don't forget the meeting!


虽然最终从XML中提取出来就是上面的内容,但是我们从上面的内容根本看不出这是什么。
2、数据做成XML有助于改变其内容
如果我们现在想再添加一项:时间。在XML中我们可以这样:

[html]view plaincopyprint?

  1. <note>  
  2. <to>George</to>  
  3. <from>John</from>  
  4. <heading>Reminder</heading>  
  5. <body>Don't forget the meeting!</body>  
  6. <time>2012-12-03</time>  
  7. </note>  


<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<time>2012-12-03</time>
</note>


在我们解析的时候,只要从对应的标签“time”找就行,非常方便!这样的特点,有助于组织复杂的数据。
3、XML 与 HTML 的主要差异
XML 不是 HTML 的替代,XML 和 HTML 为不同的目的而设计,XML 被设计为传输和存储数据,其焦点是数据的内容。HTML 被设计用来显示数据,其焦点是数据的外观。HTML 旨在显示信息,而 XML 旨在传输信息。HTML的标记不是所有的都需要成对出现,XML则要求所有的标记必须成对出现,HTML标记不区分大小写,XML则 大小敏感,即区分大小写。
4、XML 文档是一种树结构
北京联动北方科技有限公司
上图表示下面的 XML 中的一本书:

[html]view plaincopyprint?

  1. <bookstore>  
  2. <book category="COOKING">  
  3.   <title lang="en">Everyday Italian</title>   
  4.   <author>Giada De Laurentiis</author>   
  5.   <year>2005</year>   
  6.   <price>30.00</price>   
  7. </book>  
  8. <book category="CHILDREN">  
  9.   <title lang="en">Harry Potter</title>   
  10.   <author>J K. Rowling</author>   
  11.   <year>2005</year>   
  12.   <price>29.99</price>   
  13. </book>  
  14. <book category="WEB">  
  15.   <title lang="en">Learning XML</title>   
  16.   <author>Erik T. Ray</author>   
  17.   <year>2003</year>   
  18.   <price>39.95</price>   
  19. </book>  
  20. </bookstore>  


<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>


二、XML的解析技术
1、大名鼎鼎的DOM技术
说它大名鼎鼎可是一点不为过,DOM 是 W3C 处理 XML 的标准 API,它是许多其它与 XML 处理相关的标准的基础,不仅是 Java,其它诸如 Javascript,PHP,MS .NET 等等语言都实现了该标准, 成为了应用最为广泛的 XML 处理方式。当然,为了能提供更多更加强大的功能,Java 对于 DOM 直接扩展工具类有很多,比如很多 Java 程序员耳熟能详的 JDOM,DOM4J 等等, 它们基本上属于对 DOM 接口功能的扩充,保留了很多 DOM API 的特性,许多原本的 DOM 程序员甚至都没有任何障碍就熟练掌握了另外两者的使用,直观、易于操作的方式使它深受广大 Java 程序员的喜爱。
2、绿色环保的 SAX
SAX 的应运而生有它特殊的需要,为什么说它绿色环保呢,这是因为 SAX 使用了最少的系统资源和最快速的解析方式对 XML 处理提供了支持。 但随之而来繁琐的查找方式也给广大程序员带来许多困扰,常常令人头痛不已,同时它对 XPath 查询功能的支持,令人们对它又爱又恨。
二种技术的比较:

DOM


优缺点:实现 W3C 标准,有多种编程语言支持这种解析方式,并且这种方法本身操作上简单快捷,十分易于初学者掌握。其处理方式是将 XML 整个作为类似树结构的方式读入内存中以便操作及解析,因此支持应用程序对 XML 数据的内容和结构进行修改,但是同时由于其需要在处理开始时将整个 XML 文件读入到内存中去进行分析,因此其在解析大数据量的 XML 文件时会遇到类似于内存泄露以及程序崩溃的风险,请对这点多加注意。
适用范围:小型 XML 文件解析、需要全解析或者大部分解析 XML、需要修改 XML 树内容以生成自己的对象模型

SAX


SAX 从根本上解决了 DOM 在解析 XML 文档时产生的占用大量资源的问题。其实现是通过类似于流解析的技术,通读整个 XML 文档树,通过事件处理器来响应程序员对于 XML 数据解析的需求。由于其不需要将整个 XML 文档读入内存当中,它对系统资源的节省是十分显而易见的,它在一些需要处理大型 XML 文档以及性能要求较高的场合有起了十分重要的作用。支持 XPath 查询的 SAX 使得开发人员更加灵活,处理起 XML 来更加的得心应手。但是同时,其仍然有一些不足之处也困扰广大的开发人员:首先是它十分复杂的 API 接口令人望而生畏,其次由于其是属于类似流解析的文件扫描方式,因此不支持应用程序对于 XML 树内容结构等的修改,可能会有不便之处。
适用范围:大型 XML 文件解析、只需要部分解析或者只想取得部分 XML 树内容、有 XPath 查询需求、有自己生成特定 XML 树对象模型的需求
三、实例运用
首先造一个xml文档出来:(books.xml放在项目根路径下,不是src)

[html]view plaincopyprint?

  1. <?xml version="1.0" encoding="UTF-8"?>   
  2.  <books>   
  3.    <book id="01" name="book1">   
  4.       <title>Harry Potter</title>   
  5.       <author>J K. Rowling</author>   
  6.    </book>   
  7.    <book id="02" name="book2">  
  8.       <title>Thinking in Java</title>  
  9.       <author>Bruke</author>  
  10.    </book>   
  11.  </books>   


<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="01" name="book1">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
<book id="02" name="book2">
<title>Thinking in Java</title>
<author>Bruke</author>
</book>
</books>

使用DOM进行解析:

[java]view plaincopyprint?

  1. /** 
  2.  * the DOM Parser Example 
  3.  * @author egg 
  4.  * email:xtfggef@gmail.com 
  5.  * microblog:http://weibo.com/xtfggef 
  6.  */ 
  7. public class DOMTest { 
  8.       
  9.        /* build a DocumentBuilderFactory */ 
  10.        DocumentBuilderFactory builderFactory = DocumentBuilderFactory 
  11.        .newInstance(); 
  12.       
  13.        public static void main(String[] args) { 
  14.              DOMTest parser = new DOMTest(); 
  15.              Document document = parser.parse("books.xml"); 
  16.              /* get root element */ 
  17.              Element rootElement = document.getDocumentElement(); 
  18.             
  19.              /* get all the nodes whose name is book */ 
  20.              NodeList nodeList = rootElement.getElementsByTagName("book"); 
  21.              if (nodeList != null) { 
  22.                    for (int i = 0; i < nodeList.getLength(); i++) { 
  23.                          /* get every node */ 
  24.                          Node node = nodeList.item(i); 
  25.                          /* get the next lever's ChildNodes */ 
  26.                          NodeList nodeList2 = node.getChildNodes(); 
  27.                          for (int j = 0; j < nodeList2.getLength(); j++) { 
  28.                                Node node2 = nodeList2.item(j); 
  29.                                if (node2.hasChildNodes()) { 
  30.                                      System.out.println(node2.getNodeName() + ":" 
  31.                                      + node2.getFirstChild().getNodeValue()); 
  32.                                } 
  33.                          } 
  34.                    } 
  35.              } 
  36.        } 
  37.       
  38.        /* Load and parse XML file into DOM */ 
  39.        public Document parse(String filePath) { 
  40.              Document document = null; 
  41.              try { 
  42.                    /* DOM parser instance */ 
  43.                    DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
  44.                    /* parse an XML file into a DOM tree */ 
  45.                    document = builder.parse(new File(filePath)); 
  46.              } catch (ParserConfigurationException e) { 
  47.                    e.printStackTrace(); 
  48.              } catch (SAXException e) { 
  49.                    e.printStackTrace(); 
  50.              } catch (IOException e) { 
  51.                    e.printStackTrace(); 
  52.              } 
  53.              return document; 
  54.        } 


/**
* the DOM Parser Example
* @author egg
* email:xtfggef@gmail.com
* microblog:http://weibo.com/xtfggef
*/
public class DOMTest {
       /* build a DocumentBuilderFactory */
       DocumentBuilderFactory builderFactory = DocumentBuilderFactory
       .newInstance();
       public static void main(String[] args) {
             DOMTest parser = new DOMTest();
             Document document = parser.parse("books.xml");
             /* get root element */
             Element rootElement = document.getDocumentElement();
             /* get all the nodes whose name is book */
             NodeList nodeList = rootElement.getElementsByTagName("book");
             if (nodeList != null) {
                   for (int i = 0; i < nodeList.getLength(); i++) {
                         /* get every node */
                         Node node = nodeList.item(i);
                         /* get the next lever's ChildNodes */
                         NodeList nodeList2 = node.getChildNodes();
                         for (int j = 0; j < nodeList2.getLength(); j++) {
                               Node node2 = nodeList2.item(j);
                               if (node2.hasChildNodes()) {
                                     System.out.println(node2.getNodeName() + ":"
                                     + node2.getFirstChild().getNodeValue());
                               }
                         }
                   }
             }
       }
       /* Load and parse XML file into DOM */
       public Document parse(String filePath) {
             Document document = null;
             try {
                   /* DOM parser instance */
                   DocumentBuilder builder = builderFactory.newDocumentBuilder();
                   /* parse an XML file into a DOM tree */
                   document = builder.parse(new File(filePath));
             } catch (ParserConfigurationException e) {
                   e.printStackTrace();
             } catch (SAXException e) {
             e.printStackTrace();
       } catch (IOException e) {
       e.printStackTrace();
}
return document;
}
}

输出:

 title:Harry Potter
author:J K. Rowling
title:Thinking in Java
author:Bruke


想弄懂xml的解析,需要先清楚几个概念:节点、属性,如下图:
北京联动北方科技有限公司
这样结合上面的例子就容易理解了,给一个例子,大家自己去练习下:

[html]view plaincopyprint?

  1. <?xml version="1.0" encoding="UTF-8"?>   
  2.  <books>   
  3.    <name>Think in C++</name>  
  4.    <price>100</price>  
  5.    <author>brucl</author>  
  6.  </books>   


<?xml version="1.0" encoding="UTF-8"?>
<books>
<name>Think in C++</name>
<price>100</price>
<author>brucl</author>
</books>


使用SAX进行解析:

[java]view plaincopyprint?

  1. public class SAXTest { 
  2.       
  3.        class BookHandler extends DefaultHandler { 
  4.              private List<String> nameList; 
  5.              private boolean title = false; 
  6.             
  7.              public List<String> getNameList() { 
  8.                    return nameList; 
  9.              } 
  10.             
  11.              // Called at start of an XML document 
  12.              @Override 
  13.              public void startDocument() throws SAXException { 
  14.                    System.out.println("Start parsing document..."); 
  15.                    nameList = new ArrayList<String>(); 
  16.              } 
  17.             
  18.              // Called at end of an XML document 
  19.              @Override 
  20.              public void endDocument() throws SAXException { 
  21.                    System.out.println("End"); 
  22.              } 
  23.             
  24.              @Override 
  25.              public void startElement(String uri, String localName, String qName, 
  26.              Attributes atts) throws SAXException { 
  27.                    // Using qualified name because we are not using xmlns prefixes 
  28.                    // here. 
  29.                    if (qName.equals("title")) { 
  30.                          title = true; 
  31.                    } 
  32.              } 
  33.             
  34.              @Override 
  35.              public void endElement(String namespaceURI, String localName, 
  36.              String qName) throws SAXException { 
  37.                    // End of processing current element 
  38.                    if (title) { 
  39.                          title = false; 
  40.                    } 
  41.              } 
  42.             
  43.              @Override 
  44.              public void characters(char[] ch, int start, int length) { 
  45.                    // Processing character data inside an element 
  46.                    if (title) { 
  47.                          String bookTitle = new String(ch, start, length); 
  48.                          System.out.println("Book title: " + bookTitle); 
  49.                          nameList.add(bookTitle); 
  50.                    } 
  51.              } 
  52.             
  53.        } 
  54.       
  55.        public static void main(String[] args) throws SAXException, IOException { 
  56.              XMLReader parser = XMLReaderFactory.createXMLReader(); 
  57.              BookHandler bookHandler = (new SAXTest()).new BookHandler(); 
  58.              parser.setContentHandler(bookHandler); 
  59.              parser.parse("books.xml"); 
  60.              System.out.println(bookHandler.getNameList()); 
  61.        } 


public class SAXTest {
       class BookHandler extends DefaultHandler {
             private List<String> nameList;
             private boolean title = false;
             public List<String> getNameList() {
                   return nameList;
             }
             // Called at start of an XML document
             @Override
             public void startDocument() throws SAXException {
                   System.out.println("Start parsing document...");
                   nameList = new ArrayList<String>();
             }
             // Called at end of an XML document
             @Override
             public void endDocument() throws SAXException {
                   System.out.println("End");
             }
             @Override
             public void startElement(String uri, String localName, String qName,
             Attributes atts) throws SAXException {
                   // Using qualified name because we are not using xmlns prefixes
                   // here.
                   if (qName.equals("title")) {
                         title = true;
                   }
             }
             @Override
             public void endElement(String namespaceURI, String localName,
             String qName) throws SAXException {
                   // End of processing current element
                   if (title) {
                         title = false;
                   }
             }
             @Override
             public void characters(char[] ch, int start, int length) {
                   // Processing character data inside an element
                   if (title) {
                         String bookTitle = new String(ch, start, length);
                         System.out.println("Book title: " + bookTitle);
                         nameList.add(bookTitle);
                   }
             }
       }
       public static void main(String[] args) throws SAXException, IOException {
             XMLReader parser = XMLReaderFactory.createXMLReader();
             BookHandler bookHandler = (new SAXTest()).new BookHandler();
             parser.setContentHandler(bookHandler);
             parser.parse("books.xml");
             System.out.println(bookHandler.getNameList());
       }
}


XML的打包

[java]view plaincopyprint?

  1. public class SAXGeneratorXml { 
  2.        public static void main(String[] args) { 
  3.              String outputPath = "persons.xml"; 
  4.              generateXml(outputPath); 
  5.        } 
  6.       
  7.        public static void generateXml(String outputPath) { 
  8.              try { 
  9.                    Person[] arr = new Person[] { new Person("egg", 22), 
  10.                    new Person("niu", 21) }; 
  11.                    List<Person> list = Arrays.asList(arr);// 将数组转换成List 
  12.                    Document doc = generateXml(list);// 生成XML文件 
  13.                    outputXml(doc, outputPath);// 将文件输出到指定的路径 
  14.              } catch (Exception e) { 
  15.                    System.err.println("出现异常"); 
  16.              } 
  17.        } 
  18.       
  19.        /** 
  20.        * 将XML文件输出到指定的路径 
  21.        * @param doc 
  22.        * @param fileName 
  23.        * @throws Exception 
  24.        */ 
  25.        private static void outputXml(Document doc, String fileName) 
  26.        throws Exception { 
  27.              TransformerFactory tf = TransformerFactory.newInstance(); 
  28.              Transformer transformer = tf.newTransformer(); 
  29.              DOMSource source = new DOMSource(doc); 
  30.              transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
  31.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");// 设置文档的换行与缩进 
  32.              PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); 
  33.              StreamResult result = new StreamResult(pw); 
  34.              transformer.transform(source, result); 
  35.              System.out.println("生成XML文件成功!"); 
  36.        } 
  37.       
  38.        /** 
  39.        * 生成XML文件 
  40.        * @param list 
  41.        * @return 
  42.        */ 
  43.        public static Document generateXml(List<Person> list) { 
  44.              Document doc = null; 
  45.              Element root = null; 
  46.              try { 
  47.                    DocumentBuilderFactory factory = DocumentBuilderFactory 
  48.                    .newInstance(); 
  49.                    DocumentBuilder builder = factory.newDocumentBuilder(); 
  50.                    doc = builder.newDocument(); 
  51.                    root = doc.createElement("person"); 
  52.                    doc.appendChild(root); 
  53.              } catch (Exception e) { 
  54.                    e.printStackTrace(); 
  55.                   return null;// 如果出现异常,则不再往下执行 
  56.              } 
  57.             
  58.              int len = list.size(); 
  59.              Element element; 
  60.              for (int i = 0; i < len; i++) { 
  61.                    Person person = list.get(i); 
  62.                    element = doc.createElement("person" + (i + 1)); 
  63.                    element.setAttribute("age", "" + person.getAge()); 
  64.                    element.setAttribute("name", person.getName()); 
  65.                    root.appendChild(element); 
  66.              } 
  67.              return doc; 
  68.        } 


public class SAXGeneratorXml {
       public static void main(String[] args) {
             String outputPath = "persons.xml";
             generateXml(outputPath);
       }
       public static void generateXml(String outputPath) {
             try {
                   Person[] arr = new Person[] { new Person("egg", 22),
                   new Person("niu", 21) };
                   List<Person> list = Arrays.asList(arr);// 将数组转换成List
                   Document doc = generateXml(list);// 生成XML文件
                   outputXml(doc, outputPath);// 将文件输出到指定的路径
             } catch (Exception e) {
             System.err.println("出现异常");
       }
}
/**
* 将XML文件输出到指定的路径
* @param doc
* @param fileName
* @throws Exception
*/
private static void outputXml(Document doc, String fileName)
throws Exception {
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       DOMSource source = new DOMSource(doc);
       transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
       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文件成功!");
}
/**
* 生成XML文件
* @param list
* @return
*/
public static Document generateXml(List<Person> list) {
       Document doc = null;
       Element root = null;
       try {
             DocumentBuilderFactory factory = DocumentBuilderFactory
             .newInstance();
             DocumentBuilder builder = factory.newDocumentBuilder();
             doc = builder.newDocument();
             root = doc.createElement("person");
             doc.appendChild(root);
       } catch (Exception e) {
       e.printStackTrace();
       return null;// 如果出现异常,则不再往下执行
}
int len = list.size();
Element element;
for (int i = 0; i < len; i++) {
       Person person = list.get(i);
       element = doc.createElement("person" + (i + 1));
       element.setAttribute("age", "" + person.getAge());
       element.setAttribute("name", person.getName());
       root.appendChild(element);
}
return doc;
}
}



该贴被linjun编辑于2013-1-7 16:39:26




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