Java高级特性之解析XML

来源:互联网 发布:用mac给iphone装软件 编辑:程序博客网 时间:2024/06/06 04:12

XML与Java的渊源:

我们来看XML是网络传输的一种数据规范,或者也叫可扩展的标记语言。可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。 XML使用DTD(document type definition)文档类型定义来组织数据;格式统一,跨平台和语言,早已成为业界公认的标准。
XML是标准通用标记语言 (SGML) 的子集,非常适合 Web 传输。XML 提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。

早在1998年,W3C就发布了XML1.0规范,使用它来简化Internet的文档信息传输。而我们的Java正式诞生时间是1996年1月,Sun公司发布了Java的第一个开发工具包(JDK 1.0),这是Java发展历程中的重要里程碑,标志着Java成为一种独立的开发工具。在第一版的JDK里面java已经开始支持解析xml了,但是效率非常低,而且功能使用起来也不是那么友好,不过没关系谁叫java是开源的啦,在当时有IBM喝Apache公司一直在帮助开发用于XML处理的高质量java库。

XML概述:

XML 文件由内容和标记组成。您通过以标记包围内容的方式将大部分内容包含在元素中。XML格式能够表达层次结构,并且重复的元素不会被曲解。XML文件的格式非常直观,它与HTML文件非常相似。因为XML和HTML格式是古老的标准通用标记语言所诞生的衍生语言。

解析XML文档:

要处理XML文档,首先就要去解析它。解析器的步骤如下:

1.它读取一个文件

2.校验这个文件的格式

3.将其拆分组成各种元素,使得程序员可以使用

Java库提供了两种XML解析器:

像文档对象类型解析器这样的树形解析器,它们将读取的XML文档转换成树结构。

像XML简单API解析器这样的流机制解析器,它们在读入XML文档时生成相应的事件。


DOM解析:

这里如果对DOM不是很熟悉的话,可以去看看我写的关于DOM的文档点击打开链接



因为关于DOM的包比较多,所以我会把引入的路径也给贴出来:

import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class Test {private Document document;private String fileName;public void init() {try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();this.document = builder.newDocument();} catch (ParserConfigurationException e) {System.out.println(e.getMessage());}}public void createXml(String fileName) {Element root = this.document.createElement("employees");this.document.appendChild(root);Element employee = this.document.createElement("employee");Element name = this.document.createElement("name");name.appendChild(this.document.createTextNode("张三"));employee.appendChild(name);Element sex = this.document.createElement("sex");sex.appendChild(this.document.createTextNode("m"));employee.appendChild(sex);Element age = this.document.createElement("age");age.appendChild(this.document.createTextNode("30"));employee.appendChild(age);root.appendChild(employee);TransformerFactory tf = TransformerFactory.newInstance();try {javax.xml.transform.Transformer transformer = tf.newTransformer();DOMSource source = new DOMSource(document);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文件成功!");} catch (TransformerConfigurationException e) {System.out.println(e.getMessage());} catch (IllegalArgumentException e) {System.out.println(e.getMessage());} catch (FileNotFoundException e) {System.out.println(e.getMessage());} catch (TransformerException e) {System.out.println(e.getMessage());}}public void parserXml(String fileName) {try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document document = db.parse(fileName);NodeList employees = document.getChildNodes();for (int i = 0; i < employees.getLength(); i++) {Node employee = employees.item(i);NodeList employeeInfo = employee.getChildNodes();for (int j = 0; j < employeeInfo.getLength(); j++) {Node node = employeeInfo.item(j);NodeList employeeMeta = node.getChildNodes();for (int k = 0; k < employeeMeta.getLength(); k++) {System.out.println(employeeMeta.item(k).getNodeName()+ ":" + employeeMeta.item(k).getTextContent());}}}System.out.println("解析完毕");} catch (FileNotFoundException e) {System.out.println(e.getMessage());} catch (ParserConfigurationException e) {System.out.println(e.getMessage());} catch (SAXException e) {System.out.println(e.getMessage());} catch (IOException e) {System.out.println(e.getMessage());}}public static void main(String[] args) {String fileName=new String("test\\student.xml"); Test test=new Test(); test.init();test.createXml(fileName); test.parserXml(fileName);}}

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

SAX生成和解析XML文档

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

Java代码

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;public class SaxDemo {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();}}public static void main(String[] args) {String fileName=new String("C:\\Users\\Desktop\\test\\student.xml");SaxDemo demo=new SaxDemo();demo.createXml(fileName);demo.parserXml(fileName);}}class MySAXHandler extends DefaultHandler {boolean hasAttribute = false;Attributes attributes = null;@Overridepublic void startDocument() throws SAXException {System.out.println("文档开始打印了");}@Overridepublic void endDocument() throws SAXException {System.out.println("文档打印结束了");}@Overridepublic 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;}}@Overridepublic 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));}}}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {System.out.println(new String(ch, start, length));}}

DOM4J生成和解析XML文档

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

Java代码

import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.Writer;import java.util.Iterator;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class Dom4jDemo {public void createXml(String fileName) {Document document = DocumentHelper.createDocument();Element employees = document.addElement("employees");Element employee = employees.addElement("employee");Element name = employee.addElement("name");name.setText("ddvip");Element sex = employee.addElement("sex");sex.setText("m");Element age = employee.addElement("age");age.setText("29");try {Writer fileWriter = new FileWriter(fileName);XMLWriter xmlWriter = new XMLWriter(fileWriter);xmlWriter.write(document);xmlWriter.close();} catch (IOException e) {System.out.println(e.getMessage());}}public void parserXml(String fileName) {File inputXml = new File(fileName);SAXReader saxReader = new SAXReader();try {Document document = saxReader.read(inputXml);Element employees = document.getRootElement();for (Iterator i = employees.elementIterator(); i.hasNext();) {Element employee = (Element) i.next();for (Iterator j = employee.elementIterator(); j.hasNext();) {Element node = (Element) j.next();System.out.println(node.getName() + ":" + node.getText());}}} catch (DocumentException e) {System.out.println(e.getMessage());}System.out.println("dom4j parserXml");}}

JDOM生成和解析XML  

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

<pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 16px; line-height: 30px; text-align: justify;">import java.io.FileNotFoundException;   import java.io.FileOutputStream;   import java.io.IOException;   import java.util.List;   import org.jdom.Document;   import org.jdom.Element;   import org.jdom.JDOMException;   import org.jdom.input.SAXBuilder;   import org.jdom.output.XMLOutputter;     public class JDomDemo {   public void createXml(String fileName) {   Document document;   Element  root;   root=new Element("employees");   document=new Document(root);   Element employee=new Element("employee");   root.addContent(employee);   Element name=new Element("name");   name.setText("ddvip");   employee.addContent(name);   Element sex=new Element("sex");   sex.setText("m");   employee.addContent(sex);   Element age=new Element("age");   age.setText("23");   employee.addContent(age);   XMLOutputter XMLOut = new XMLOutputter();   try {   XMLOut.output(document, new FileOutputStream(fileName));   } catch (FileNotFoundException e) {   e.printStackTrace();   } catch (IOException e) {   e.printStackTrace();   }   }   public void parserXml(String fileName) {   SAXBuilder builder=new SAXBuilder(false);    try {   Document document=builder.build(fileName);   Element employees=document.getRootElement();    List employeeList=employees.getChildren("employee");   for(int i=0;iElement employee=(Element)employeeList.get(i);   List employeeInfo=employee.getChildren();   for(int j=0;jSystem.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());   }   }   } catch (JDOMException e) {   e.printStackTrace();   } catch (IOException e) {   e.printStackTrace();   }    }   }     


验证XML文档:

以上的方式都可以去遍历DMO文档树,XML解析器有一个强大的文档验证,那就是文档类型定义(DTD)或XML Schema定义。DTD或schema包含了用于解释文档应如何构成的规则这些规则指定了每个元素的合法子元素和属性。例如

<!ELEMENT font(name,size)>

这个规则表示,一个font元素必须总是有两个子元素,分别是name和size。

XML Schema

XML Schema比起DTD语法要复杂的许多,而且实际开发中使用的很少,如果有兴趣的请参考www.w3.org/TR/xmlschema-0上的指南。或者参考w3c的官方网站;

如果要在文档中引入schema文件,需要在根元素中添加属性。

<?xml version="1.0" encoding="utf-8"?><configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="config.xsd"><employees><employee><name>张三</name><sex>m</sex><age>30</age></employee></employees></configuration>
这个声明说明该xml会以文件config.xsd来验证文档;





可以像这样去定义它;具体的验证会放在下次再总结;




0 0
原创粉丝点击