Java解析XMLの四つの方法
55985 ワード
XMLは現在、共通のデータ交換形式になっています。プラットフォームは無関係で、言語は無関係で、システムは無関係で、データ統合と相互作用に大きな便利をもたらしています。XML自体の文法知識と技術の詳細については、関連する技術文献を読む必要があります。この中にはDOM(Dockment Object Model)、DodD(Dock Type Definition)、SAX(Simple API for XML)、XSD(Xml Schema Definition)、XSLT(Extens 3 Styclesheet Latma)があります。http://www.w3.orgより多くの情報を取得します。
XMLは異なる言語で解析方式が同じです。実現された文法が違っているだけです。基本的な解析方法は二つあります。一つはSAXといい、もう一つはDOMといいます。SAXはイベントフローの解析に基づいており、DOMはXMLドキュメントツリー構造の解析に基づいている。私たちXMLの内容と構造は以下の通りであると仮定します。
本論文はJAVA言語を使用して、DOMとSAXのXML文書の生成と解析を実現する。 まずXMLドキュメントを操作するインターフェースXml Dcumentを定義します。XMLドキュメントの作成と解析のインターフェースを定義しています。
1.DOM作成と解析XMLドキュメント
XMLドキュメントの解析済みバージョンのためのインターフェースのセットが定義されています。解析器はドキュメント全体を読み込んで、メモリに存在するツリー構造を構築し、コードはDOMインターフェースを使ってこのツリー構造を操作することができます。利点:全体のドキュメントツリーはメモリの中にあり、操作しやすいです。削除、変更、並び替えなど様々な機能をサポートします。短所:ドキュメント全体をメモリに取り込み(不要なノードを含む)、時間と空間を無駄にします。使用する場合:ドキュメントを解析すると、これらのデータにも複数アクセスする必要があります。ハードウェア資源が十分です(メモリ、CPU)。
2.SAX作成と解析XMLドキュメント
DOMの問題を解決するためにSAXが発生しました。SAX、イベント駆動。解析器が元素の開始、元素の終了、テキスト、文書の開始または終了などを発見した場合、イベントを送信し、プログラマはこれらのイベントに応答するコードを作成し、データを保存します。利点:ドキュメント全体に事前に配置しなくても、リソースが少ないです。SAX解像器コードはDOM解像器コードより小さいので、Applet、ダウンロードに適しています。短所:長く続かない;イベント後、データを保存していないとデータが無くなります。無状態性イベントからはテキストしか入手できませんが、どの要素に該当するかは分かりません。使用場所:Apple;XMLドキュメントの少量の内容だけが必要で、めったに振り返らないです。マシンのメモリが少ないです
Javaコード
XMLは異なる言語で解析方式が同じです。実現された文法が違っているだけです。基本的な解析方法は二つあります。一つはSAXといい、もう一つはDOMといいます。SAXはイベントフローの解析に基づいており、DOMはXMLドキュメントツリー構造の解析に基づいている。私たちXMLの内容と構造は以下の通りであると仮定します。
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>ddviplinux</name>
<sex>m</sex>
<age>30</age>
</employee>
</employees>
本論文はJAVA言語を使用して、DOMとSAXのXML文書の生成と解析を実現する。 まずXMLドキュメントを操作するインターフェースXml Dcumentを定義します。XMLドキュメントの作成と解析のインターフェースを定義しています。
package com.alisoft.facepay.framework.bean;
/**
*
* @author hongliang.dinghl
* XML
*/
public interface XmlDocument {
/**
* XML
* @param fileName
*/
public void createXml(String fileName);
/**
* XML
* @param fileName
*/
public void parserXml(String fileName);
}
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 *
25 * @author hongliang.dinghl
26 * DOM XML
27 */
28 public class DomDemo implements XmlDocument {
29 private Document document;
30 private String fileName;
31 public void init() {
32 try {
33 DocumentBuilderFactory factory = DocumentBuilderFactory
34 .newInstance();
35 DocumentBuilder builder = factory.newDocumentBuilder();
36 this.document = builder.newDocument();
37 } catch (ParserConfigurationException e) {
38 System.out.println(e.getMessage());
39 }
40 }
41 public void createXml(String fileName) {
42 Element root = this.document.createElement("employees");
43 this.document.appendChild(root);
44 Element employee = this.document.createElement("employee");
45 Element name = this.document.createElement("name");
46 name.appendChild(this.document.createTextNode(" "));
47 employee.appendChild(name);
48 Element sex = this.document.createElement("sex");
49 sex.appendChild(this.document.createTextNode("m"));
50 employee.appendChild(sex);
51 Element age = this.document.createElement("age");
52 age.appendChild(this.document.createTextNode("30"));
53 employee.appendChild(age);
54 root.appendChild(employee);
55 TransformerFactory tf = TransformerFactory.newInstance();
56 try {
57 Transformer transformer = tf.newTransformer();
58 DOMSource source = new DOMSource(document);
59 transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
60 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
61 PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
62 StreamResult result = new StreamResult(pw);
63 transformer.transform(source, result);
64 System.out.println(" XML !");
65 } catch (TransformerConfigurationException e) {
66 System.out.println(e.getMessage());
67 } catch (IllegalArgumentException e) {
68 System.out.println(e.getMessage());
69 } catch (FileNotFoundException e) {
70 System.out.println(e.getMessage());
71 } catch (TransformerException e) {
72 System.out.println(e.getMessage());
73 }
74 }
75 public void parserXml(String fileName) {
76 try {
77 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
78 DocumentBuilder db = dbf.newDocumentBuilder();
79 Document document = db.parse(fileName);
80 NodeList employees = document.getChildNodes();
81 for (int i = 0; i < employees.getLength(); i++) {
82 Node employee = employees.item(i);
83 NodeList employeeInfo = employee.getChildNodes();
84 for (int j = 0; j < employeeInfo.getLength(); j++) {
85 Node node = employeeInfo.item(j);
86 NodeList employeeMeta = node.getChildNodes();
87 for (int k = 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 (FileNotFoundException e) {
95 System.out.println(e.getMessage());
96 } catch (ParserConfigurationException e) {
97 System.out.println(e.getMessage());
98 } catch (SAXException e) {
99 System.out.println(e.getMessage());
100 } catch (IOException e) {
101 System.out.println(e.getMessage());
102 }
103 }
104 }
2.SAX作成と解析XMLドキュメント
DOMの問題を解決するためにSAXが発生しました。SAX、イベント駆動。解析器が元素の開始、元素の終了、テキスト、文書の開始または終了などを発見した場合、イベントを送信し、プログラマはこれらのイベントに応答するコードを作成し、データを保存します。利点:ドキュメント全体に事前に配置しなくても、リソースが少ないです。SAX解像器コードはDOM解像器コードより小さいので、Applet、ダウンロードに適しています。短所:長く続かない;イベント後、データを保存していないとデータが無くなります。無状態性イベントからはテキストしか入手できませんが、どの要素に該当するかは分かりません。使用場所:Apple;XMLドキュメントの少量の内容だけが必要で、めったに振り返らないです。マシンのメモリが少ないです
Javaコード
1 package com.alisoft.facepay.framework.bean;
2 import java.io.FileInputStream;
3 import java.io.FileNotFoundException;
4 import java.io.IOException;
5 import java.io.InputStream;
6
7 import javax.xml.parsers.ParserConfigurationException;
8 import javax.xml.parsers.SAXParser;
9 import javax.xml.parsers.SAXParserFactory;
10
11 import org.xml.sax.Attributes;
12 import org.xml.sax.SAXException;
13 import org.xml.sax.helpers.DefaultHandler;
14 /**
15 *
16 * @author hongliang.dinghl
17 * SAX
18 */
19 public class SaxDemo implements XmlDocument {
20
21 public void createXml(String fileName) {
22 System.out.println("<<"+filename+">>");
23 }
24
25 public void parserXml(String fileName) {
26 SAXParserFactory saxfac = SAXParserFactory.newInstance();
27
28 try {
29
30 SAXParser saxparser = saxfac.newSAXParser();
31
32 InputStream is = new FileInputStream(fileName);
33
34 saxparser.parse(is, new MySAXHandler());
35
36 } catch (ParserConfigurationException e) {
37
38 e.printStackTrace();
39
40 } catch (SAXException e) {
41
42 e.printStackTrace();
43
44 } catch (FileNotFoundException e) {
45
46 e.printStackTrace();
47
48 } catch (IOException e) {
49
50 e.printStackTrace();
51
52 }
53
54 }
55
56 }
57
58 class MySAXHandler extends DefaultHandler {
59
60 boolean hasAttribute = false;
61
62 Attributes attributes = null;
63
64 public void startDocument() throws SAXException {
65
66 System.out.println(" ");
67
68 }
69
70 public void endDocument() throws SAXException {
71
72 System.out.println(" ");
73
74 }
75
76 public void startElement(String uri, String localName, String qName,
77
78 Attributes attributes) throws SAXException {
79
80 if (qName.equals("employees")) {
81
82 return;
83
84 }
85
86 if (qName.equals("employee")) {
87
88 System.out.println(qName);
89
90 }
91
92 if (attributes.getLength() > 0) {
93
94 this.attributes = attributes;
95
96 this.hasAttribute = true;
97
98 }
99
100 }
101
102 public void endElement(String uri, String localName, String qName)
103
104 throws SAXException {
105
106 if (hasAttribute && (attributes != null)) {
107
108 for (int i = 0; i < attributes.getLength(); i++) {
109
110 System.out.println(attributes.getQName(0)
111 + attributes.getValue(0));
112
113 }
114
115 }
116
117 }
118
119 public void characters(char[] ch, int start, int length)
120
121 throws SAXException {
122
123 System.out.println(new String(ch, start, length));
124
125 }
126
127 }
3.DOM 4 J XMLドキュメントの生成と解析1 package com.alisoft.facepay.framework.bean; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import javax.xml.parsers.ParserConfigurationException; 7 import javax.xml.parsers.SAXParser; 8 import javax.xml.parsers.SAXParserFactory; 9 import org.xml.sax.Attributes; 10 import org.xml.sax.SAXException; 11 import org.xml.sax.helpers.DefaultHandler; 12 /** 13 * 14 * @author hongliang.dinghl 15 * SAX 16 */ 17 public class SaxDemo implements XmlDocument { 18 public void createXml(String fileName) { 19 System.out.println("<<"+filename+">>"); 20 } 21 public void parserXml(String fileName) { 22 SAXParserFactory saxfac = SAXParserFactory.newInstance(); 23 try { 24 SAXParser saxparser = saxfac.newSAXParser(); 25 InputStream is = new FileInputStream(fileName); 26 saxparser.parse(is, new MySAXHandler()); 27 } catch (ParserConfigurationException e) { 28 e.printStackTrace(); 29 } catch (SAXException e) { 30 e.printStackTrace(); 31 } catch (FileNotFoundException e) { 32 e.printStackTrace(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 } 37 } 38 class MySAXHandler extends DefaultHandler { 39 boolean hasAttribute = false; 40 Attributes attributes = null; 41 public void startDocument() throws SAXException { 42 System.out.println(" "); 43 } 44 public void endDocument() throws SAXException { 45 System.out.println(" "); 46 } 47 public void startElement(String uri, String localName, String qName, 48 Attributes attributes) throws SAXException { 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 public void endElement(String uri, String localName, String qName) 61 throws SAXException { 62 if (hasAttribute && (attributes != null)) { 63 for (int i = 0; i < attributes.getLength(); i++) { 64 System.out.println(attributes.getQName(0) 65 + attributes.getValue(0)); 66 } 67 } 68 } 69 public void characters(char[] ch, int start, int length) 70 throws SAXException { 71 System.out.println(new String(ch, start, length)); 72 } 73 }
DOM 4 Jは非常に優れたJava XML APIで、優れた性能、強力で使いやすいという特徴を持っています。同時に、オープンソースコードのソフトウェアです。今はますます多くのJavaソフトウェアがDOM 4 Jを使ってXMLを読み、書くことができます。特にSunのJAXMもDOM 4 Jを使っています。
Javaコード4.JDOM生成と解析XML1 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 8 import org.dom4j.Document; 9 import org.dom4j.DocumentException; 10 import org.dom4j.DocumentHelper; 11 import org.dom4j.Element; 12 import org.dom4j.io.SAXReader; 13 import org.dom4j.io.XMLWriter; 14 /** 15 * 16 * @author hongliang.dinghl 17 * Dom4j XML XML 18 */ 19 public class Dom4jDemo implements XmlDocument { 20 21 public void createXml(String fileName) { 22 Document document = DocumentHelper.createDocument(); 23 Element employees=document.addElement("employees"); 24 Element employee=employees.addElement("employee"); 25 Element name= employee.addElement("name"); 26 name.setText("ddvip"); 27 Element sex=employee.addElement("sex"); 28 sex.setText("m"); 29 Element age=employee.addElement("age"); 30 age.setText("29"); 31 try { 32 Writer fileWriter=new FileWriter(fileName); 33 XMLWriter xmlWriter=new XMLWriter(fileWriter); 34 xmlWriter.write(document); 35 xmlWriter.close(); 36 } catch (IOException e) { 37 38 System.out.println(e.getMessage()); 39 } 40 41 42 } 43 44 45 public void parserXml(String fileName) { 46 File inputXml=new File(fileName); 47 SAXReader saxReader = new SAXReader(); 48 try { 49 Document document = saxReader.read(inputXml); 50 Element employees=document.getRootElement(); 51 for(Iterator i = employees.elementIterator(); i.hasNext();){ 52 Element employee = (Element) i.next(); 53 for(Iterator j = employee.elementIterator(); j.hasNext();){ 54 Element node=(Element) j.next(); 55 System.out.println(node.getName()+":"+node.getText()); 56 } 57 58 } 59 } catch (DocumentException e) { 60 System.out.println(e.getMessage()); 61 } 62 System.out.println("dom4j parserXml"); 63 } 64 }
DOM、SAXの符号量を減らすために、JDOMが現れました。利点:20-80原則、大幅にコード量を削減します。使用の場合:解決、作成などの機能は簡単ですが、下の階では、JDOMはSAX(最も一般的)、DOM、Xanan文書を使用します。1 package com.alisoft.facepay.framework.bean; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.util.List; 7 8 import org.jdom.Document; 9 import org.jdom.Element; 10 import org.jdom.JDOMException; 11 import org.jdom.input.SAXBuilder; 12 import org.jdom.output.XMLOutputter; 13 /** 14 * 15 * @author hongliang.dinghl 16 * JDOM XML 17 * 18 */ 19 public class JDomDemo implements XmlDocument { 20 21 public void createXml(String fileName) { 22 Document document; 23 Element root; 24 root=new Element("employees"); 25 document=new Document(root); 26 Element employee=new Element("employee"); 27 root.addContent(employee); 28 Element name=new Element("name"); 29 name.setText("ddvip"); 30 employee.addContent(name); 31 Element sex=new Element("sex"); 32 sex.setText("m"); 33 employee.addContent(sex); 34 Element age=new Element("age"); 35 age.setText("23"); 36 employee.addContent(age); 37 XMLOutputter XMLOut = new XMLOutputter(); 38 try { 39 XMLOut.output(document, new FileOutputStream(fileName)); 40 } catch (FileNotFoundException e) { 41 e.printStackTrace(); 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 46 } 47 48 public void parserXml(String fileName) { 49 SAXBuilder builder=new SAXBuilder(false); 50 try { 51 Document document=builder.build(fileName); 52 Element employees=document.getRootElement(); 53 List employeeList=employees.getChildren("employee"); 54 for(int i=0;i<employeelist.size();i++){ <br="">Element employee=(Element)employeeList.get(i); 55 List employeeInfo=employee.getChildren(); 56 for(int j=0;j<employeeinfo.size();j++){ <br="">System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue()); 57 58 } 59 } 60 } catch (JDOMException e) { 61 62 e.printStackTrace(); 63 } catch (IOException e) { 64 65 e.printStackTrace(); 66 } 67 68 } 69 }