解析XML的几种方式

article/2025/9/27 22:19:24
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的内容和结构如下:

[html] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  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>  
<?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文档的接口XmlDocument 它定义了XML文档的建立与解析的接口。

[java] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  
  3. * @author hongliang.dinghl  
  4. * 定义XML文档建立与解析的接口  
  5. */   
  6. public interface XmlDocument {   
  7. /**  
  8. * 建立XML文档  
  9. * @param fileName 文件全路径名称  
  10. */   
  11. public void createXml(String fileName);   
  12. /**  
  13. * 解析XML文档  
  14. * @param fileName 文件全路径名称  
  15. */   
  16. public void parserXml(String fileName);   
  17. }   
/** 
* 
* @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)。


[java] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import java.io.FileInputStream;   
  2. import java.io.FileNotFoundException;   
  3. import java.io.FileOutputStream;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.io.PrintWriter;   
  7. import javax.xml.parsers.DocumentBuilder;   
  8. import javax.xml.parsers.DocumentBuilderFactory;   
  9. import javax.xml.parsers.ParserConfigurationException;   
  10. import javax.xml.transform.OutputKeys;   
  11. import javax.xml.transform.Transformer;   
  12. import javax.xml.transform.TransformerConfigurationException;   
  13. import javax.xml.transform.TransformerException;   
  14. import javax.xml.transform.TransformerFactory;   
  15. import javax.xml.transform.dom.DOMSource;   
  16. import javax.xml.transform.stream.StreamResult;   
  17. import org.w3c.dom.Document;   
  18. import org.w3c.dom.Element;   
  19. import org.w3c.dom.Node;   
  20. import org.w3c.dom.NodeList;   
  21. import org.xml.sax.SAXException;   
  22. /**  
  23.  
  24. * @author hongliang.dinghl  
  25. * DOM生成与解析XML文档  
  26. */   
  27. public class DomDemo implements XmlDocument {   
  28. private Document document;   
  29. private String fileName;   
  30. public void init() {   
  31. try {   
  32. DocumentBuilderFactory factory = DocumentBuilderFactory   
  33. .newInstance();   
  34. DocumentBuilder builder = factory.newDocumentBuilder();   
  35. this.document = builder.newDocument();   
  36. catch (ParserConfigurationException e) {   
  37. System.out.println(e.getMessage());   
  38. }   
  39. }   
  40. public void createXml(String fileName) {   
  41. Element root = this.document.createElement("employees");   
  42. this.document.appendChild(root);   
  43. Element employee = this.document.createElement("employee");   
  44. Element name = this.document.createElement("name");   
  45. name.appendChild(this.document.createTextNode("丁宏亮"));   
  46. employee.appendChild(name);   
  47. Element sex = this.document.createElement("sex");   
  48. sex.appendChild(this.document.createTextNode("m"));   
  49. employee.appendChild(sex);   
  50. Element age = this.document.createElement("age");   
  51. age.appendChild(this.document.createTextNode("30"));   
  52. employee.appendChild(age);   
  53. root.appendChild(employee);   
  54. TransformerFactory tf = TransformerFactory.newInstance();   
  55. try {   
  56. Transformer transformer = tf.newTransformer();   
  57. DOMSource source = new DOMSource(document);   
  58. transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");   
  59. transformer.setOutputProperty(OutputKeys.INDENT, "yes");   
  60. PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));   
  61. StreamResult result = new StreamResult(pw);   
  62. transformer.transform(source, result);   
  63. System.out.println("生成XML文件成功!");   
  64. catch (TransformerConfigurationException e) {   
  65. System.out.println(e.getMessage());   
  66. catch (IllegalArgumentException e) {   
  67. System.out.println(e.getMessage());   
  68. catch (FileNotFoundException e) {   
  69. System.out.println(e.getMessage());   
  70. catch (TransformerException e) {   
  71. System.out.println(e.getMessage());   
  72. }   
  73. }   
  74. public void parserXml(String fileName) {   
  75. try {   
  76. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
  77. DocumentBuilder db = dbf.newDocumentBuilder();   
  78. Document document = db.parse(fileName);   
  79. NodeList employees = document.getChildNodes();   
  80. for (int i = 0; i < employees.getLength(); i++) {   
  81. Node employee = employees.item(i);   
  82. NodeList employeeInfo = employee.getChildNodes();   
  83. for (int j = 0; j < employeeInfo.getLength(); j++) {   
  84. Node node = employeeInfo.item(j);   
  85. NodeList employeeMeta = node.getChildNodes();   
  86. for (int k = 0; k < employeeMeta.getLength(); k++) {   
  87. System.out.println(employeeMeta.item(k).getNodeName()   
  88. ":" + employeeMeta.item(k).getTextContent());   
  89. }   
  90. }   
  91. }   
  92. System.out.println("解析完毕");   
  93. catch (FileNotFoundException e) {   
  94. System.out.println(e.getMessage());   
  95. catch (ParserConfigurationException e) {   
  96. System.out.println(e.getMessage());   
  97. catch (SAXException e) {   
  98. System.out.println(e.getMessage());   
  99. catch (IOException e) {   
  100. System.out.println(e.getMessage());   
  101. }   
  102. }   
  103. }   
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
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.Transformer; 
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; 
/** 
* 
* @author hongliang.dinghl 
* DOM生成与解析XML文档 
*/ 
public class DomDemo implements XmlDocument { 
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 { 
Transformer transformer = tf.newTransformer(); 
DOMSource source = new DOMSource(document); 
transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312"); 
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()); 
} 
} 
} 


2.SAX生成和解析XML文档

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

[java] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import java.io.FileInputStream;     
  2. import java.io.FileNotFoundException;     
  3. import java.io.IOException;     
  4. import java.io.InputStream;     
  5.   
  6. import javax.xml.parsers.ParserConfigurationException;     
  7. import javax.xml.parsers.SAXParser;     
  8. import javax.xml.parsers.SAXParserFactory;     
  9.   
  10. import org.xml.sax.Attributes;     
  11. import org.xml.sax.SAXException;     
  12. import org.xml.sax.helpers.DefaultHandler;     
  13. /**   
  14. *    
  15. * @author hongliang.dinghl   
  16. * SAX文档解析   
  17. */    
  18. public class SaxDemo implements XmlDocument {     
  19.   
  20. public void createXml(String fileName) {     
  21. System.out.println("<<"+filename+">>");     
  22. }     
  23.   
  24. public void parserXml(String fileName) {     
  25. SAXParserFactory saxfac = SAXParserFactory.newInstance();     
  26.   
  27. try {     
  28.   
  29. SAXParser saxparser = saxfac.newSAXParser();     
  30.   
  31. InputStream is = new FileInputStream(fileName);     
  32.   
  33. saxparser.parse(is, new MySAXHandler());     
  34.   
  35. catch (ParserConfigurationException e) {     
  36.   
  37. e.printStackTrace();     
  38.   
  39. catch (SAXException e) {     
  40.   
  41. e.printStackTrace();     
  42.   
  43. catch (FileNotFoundException e) {     
  44.   
  45. e.printStackTrace();     
  46.   
  47. catch (IOException e) {     
  48.   
  49. e.printStackTrace();     
  50.   
  51. }     
  52.   
  53. }     
  54.   
  55. }     
  56.   
  57. class MySAXHandler extends DefaultHandler {     
  58.   
  59. boolean hasAttribute = false;     
  60.   
  61. Attributes attributes = null;     
  62.   
  63. public void startDocument() throws SAXException {     
  64.   
  65. System.out.println("文档开始打印了");     
  66.   
  67. }     
  68.   
  69. public void endDocument() throws SAXException {     
  70.   
  71. System.out.println("文档打印结束了");     
  72.   
  73. }     
  74.   
  75. public void startElement(String uri, String localName, String qName,     
  76.   
  77. Attributes attributes) throws SAXException {     
  78.   
  79. if (qName.equals("employees")) {     
  80.   
  81. return;     
  82.   
  83. }     
  84.   
  85. if (qName.equals("employee")) {     
  86.   
  87. System.out.println(qName);     
  88.   
  89. }     
  90.   
  91. if (attributes.getLength() > 0) {     
  92.   
  93. this.attributes = attributes;     
  94.   
  95. this.hasAttribute = true;     
  96.   
  97. }     
  98.   
  99. }     
  100.   
  101. public void endElement(String uri, String localName, String qName)     
  102.   
  103. throws SAXException {     
  104.   
  105. if (hasAttribute && (attributes != null)) {     
  106.   
  107. for (int i = 0; i < attributes.getLength(); i++) {     
  108.   
  109. System.out.println(attributes.getQName(0)     
  110. + attributes.getValue(0));     
  111.   
  112. }     
  113.   
  114. }     
  115.   
  116. }     
  117.   
  118. public void characters(char[] ch, int start, int length)     
  119.   
  120. throws SAXException {     
  121.   
  122. System.out.println(new String(ch, start, length));     
  123.   
  124. }     
  125.   
  126. }    
  127. package com.alisoft.facepay.framework.bean;   
  128. import java.io.FileInputStream;   
  129. import java.io.FileNotFoundException;   
  130. import java.io.IOException;   
  131. import java.io.InputStream;   
  132. import javax.xml.parsers.ParserConfigurationException;   
  133. import javax.xml.parsers.SAXParser;   
  134. import javax.xml.parsers.SAXParserFactory;   
  135. import org.xml.sax.Attributes;   
  136. import org.xml.sax.SAXException;   
  137. import org.xml.sax.helpers.DefaultHandler;   
  138. /**  
  139.  
  140. * @author hongliang.dinghl  
  141. * SAX文档解析  
  142. */   
  143. public class SaxDemo implements XmlDocument {   
  144. public void createXml(String fileName) {   
  145. System.out.println("<<"+filename+">>");   
  146. }   
  147. public void parserXml(String fileName) {   
  148. SAXParserFactory saxfac = SAXParserFactory.newInstance();   
  149. try {   
  150. SAXParser saxparser = saxfac.newSAXParser();   
  151. InputStream is = new FileInputStream(fileName);   
  152. saxparser.parse(is, new MySAXHandler());   
  153. catch (ParserConfigurationException e) {   
  154. e.printStackTrace();   
  155. catch (SAXException e) {   
  156. e.printStackTrace();   
  157. catch (FileNotFoundException e) {   
  158. e.printStackTrace();   
  159. catch (IOException e) {   
  160. e.printStackTrace();   
  161. }   
  162. }   
  163. }   
  164. class MySAXHandler extends DefaultHandler {   
  165. boolean hasAttribute = false;   
  166. Attributes attributes = null;   
  167. public void startDocument() throws SAXException {   
  168. System.out.println("文档开始打印了");   
  169. }   
  170. public void endDocument() throws SAXException {   
  171. System.out.println("文档打印结束了");   
  172. }   
  173. public void startElement(String uri, String localName, String qName,   
  174. Attributes attributes) throws SAXException {   
  175. if (qName.equals("employees")) {   
  176. return;   
  177. }   
  178. if (qName.equals("employee")) {   
  179. System.out.println(qName);   
  180. }   
  181. if (attributes.getLength() > 0) {   
  182. this.attributes = attributes;   
  183. this.hasAttribute = true;   
  184. }   
  185. }   
  186. public void endElement(String uri, String localName, String qName)   
  187. throws SAXException {   
  188. if (hasAttribute && (attributes != null)) {   
  189. for (int i = 0; i < attributes.getLength(); i++) {   
  190. System.out.println(attributes.getQName(0)   
  191. + attributes.getValue(0));   
  192. }   
  193. }   
  194. }   
  195. public void characters(char[] ch, int start, int length)   
  196. throws SAXException {   
  197. System.out.println(new String(ch, start, length));   
  198. }   
  199. }   
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;   
/**  
*   
* @author hongliang.dinghl  
* 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; 
/** 
* 
* @author hongliang.dinghl 
* 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)); 
} 
} 


3.DOM4J生成和解析XML文档

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


[java] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import java.io.File;     
  2. import java.io.FileWriter;     
  3. import java.io.IOException;     
  4. import java.io.Writer;     
  5. import java.util.Iterator;     
  6.   
  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. *    
  15. * @author hongliang.dinghl   
  16. * Dom4j 生成XML文档与解析XML文档   
  17. */    
  18. public class Dom4jDemo implements XmlDocument {     
  19.   
  20. public void createXml(String fileName) {     
  21. Document document = DocumentHelper.createDocument();     
  22. Element employees=document.addElement("employees");     
  23. Element employee=employees.addElement("employee");     
  24. Element name= employee.addElement("name");     
  25. name.setText("ddvip");     
  26. Element sex=employee.addElement("sex");     
  27. sex.setText("m");     
  28. Element age=employee.addElement("age");     
  29. age.setText("29");     
  30. try {     
  31. Writer fileWriter=new FileWriter(fileName);     
  32. XMLWriter xmlWriter=new XMLWriter(fileWriter);     
  33. xmlWriter.write(document);     
  34. xmlWriter.close();     
  35. catch (IOException e) {     
  36.   
  37. System.out.println(e.getMessage());     
  38. }     
  39.   
  40.   
  41. }     
  42.   
  43.   
  44. public void parserXml(String fileName) {     
  45. File inputXml=new File(fileName);     
  46. SAXReader saxReader = new SAXReader();     
  47. try {     
  48. Document document = saxReader.read(inputXml);     
  49. Element employees=document.getRootElement();     
  50. for(Iterator i = employees.elementIterator(); i.hasNext();){     
  51. Element employee = (Element) i.next();     
  52. for(Iterator j = employee.elementIterator(); j.hasNext();){     
  53. Element node=(Element) j.next();     
  54. System.out.println(node.getName()+":"+node.getText());     
  55. }     
  56.   
  57. }     
  58. catch (DocumentException e) {     
  59. System.out.println(e.getMessage());     
  60. }     
  61. System.out.println("dom4j parserXml");     
  62. }     
  63. }     
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;   
/**  
*   
* @author hongliang.dinghl  
* Dom4j 生成XML文档与解析XML文档  
*/  
public class Dom4jDemo implements XmlDocument {   
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");   
}   
}   

4.JDOM生成和解析XML  

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

[java] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import java.io.FileNotFoundException;     
  2. import java.io.FileOutputStream;     
  3. import java.io.IOException;     
  4. import java.util.List;     
  5.   
  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. *    
  13. * @author hongliang.dinghl   
  14. * JDOM 生成与解析XML文档   
  15. *    
  16. */    
  17. public class JDomDemo implements XmlDocument {     
  18.   
  19. public void createXml(String fileName) {     
  20. Document document;     
  21. Element  root;     
  22. root=new Element("employees");     
  23. document=new Document(root);     
  24. Element employee=new Element("employee");     
  25. root.addContent(employee);     
  26. Element name=new Element("name");     
  27. name.setText("ddvip");     
  28. employee.addContent(name);     
  29. Element sex=new Element("sex");     
  30. sex.setText("m");     
  31. employee.addContent(sex);     
  32. Element age=new Element("age");     
  33. age.setText("23");     
  34. employee.addContent(age);     
  35. XMLOutputter XMLOut = new XMLOutputter();     
  36. try {     
  37. XMLOut.output(document, new FileOutputStream(fileName));     
  38. catch (FileNotFoundException e) {     
  39. e.printStackTrace();     
  40. catch (IOException e) {     
  41. e.printStackTrace();     
  42. }     
  43.   
  44. }     
  45.   
  46. public void parserXml(String fileName) {     
  47. SAXBuilder builder=new SAXBuilder(false);      
  48. try {     
  49. Document document=builder.build(fileName);     
  50. Element employees=document.getRootElement();      
  51. List employeeList=employees.getChildren("employee");     
  52. for(int i=0;iElement employee=(Element)employeeList.get(i);     
  53. List employeeInfo=employee.getChildren();     
  54. for(int j=0;jSystem.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());     
  55.   
  56. }     
  57. }     
  58. catch (JDOMException e) {     
  59.   
  60. e.printStackTrace();     
  61. catch (IOException e) {     
  62.   
  63. e.printStackTrace();     
  64. }      
  65.   
  66. }     
  67. }     
  68.     

http://chatgpt.dhexx.cn/article/ZZFOGOA0.shtml

相关文章

C# 读取XML文件的几种方式

在开发过程中&#xff0c;我们有时会需要保存到本地一些结构化数据或者配置信息&#xff0c;这时就可以选择用xml文件。当然xml的用途也不仅仅是这些。 这一篇来谈一谈关于读取xml文件的几种方式&#xff1b; 我们有以下两个文件&#xff0c;一个是带有id属性的&#xff0c;一个…

Android解析XML的三种方式

在Android中提供了三种解析XML的方式:DOM(Document Objrect Model),SAX(Simple API XML),以及Android推荐的Pull解析方式. 如图: 本篇博客使用的xml文件如下:(这里是获取网络XML)person.xml <?xml version="1.0" encoding="UTF-8"?> <pers…

XML解析之SAX方式

XML文件解析方式之一是SAX方式&#xff0c;SAX解析方式会逐行地去扫描XML文档&#xff0c;当遇到标签时会触发解析处理器&#xff0c;采用事件处理的方式解析XML (Simple API for XML) 。SAX是一个用于处理XML事件驱动的“推”模型&#xff0c;虽然不是官方标准&#xff0c;但它…

实现XML解析的几种技术

XML在各种开发中都广泛应用&#xff0c;Android也不例外。作为承载数据的一个重要角色&#xff0c;如何读写XML成为Android开发中一项重要的技能。今天就由我向大家介绍一下在Android平台下几种常见的XML解析和创建的方法。 在Android中&#xff0c;常见的XML解析器分别为SAX解…

MATLAB中的均值与方差求法(mean,var,std函数使用)

目录 均值-mean()函数的用法方差var函数std函数 均值-mean()函数的用法 对于矩阵A&#xff1a; &#xff08;1&#xff09;mean(A,1)为对矩阵A的列求均值 &#xff08;2&#xff09;mean(A,2)为对矩阵A的行求均值 &#xff08;3&#xff09;mean(A)当传入的参数只有矩阵时&a…

matlab怎么方差函数,密度函数已知,怎么用matlab求其数学期望和方差?

在没有先验知识的情况下是不可能的&#xff0c;在你已知它可能是哪种分布(或者哪些种分布之一)的情况下可以求出分布的参数www.mh456.com防采集。 因为你的是密度函2113数&#xff0c;所以不会5261是离散型随机变量&#xff0c;如果你有4102概率密度函数的表达式的话&#xff0…

matlab怎么算方差和标准差,matlab怎么求矩阵的均值和标准差 看完你就知道了

有时候我们在使用matlab编程计算的时候&#xff0c;想求矩阵的均值和方差&#xff0c;怎么求呢&#xff0c;下面来分享一下方法 工具/材料 matlab 求矩阵的均值和标准差方法 matlab求矩阵均值方法 01 第一步打开matlab命令行窗口&#xff0c;新建一个a[1 2 3;4 5 6;7 8 9]矩阵&…

剩余方差matlab,用matlab的var函数求方差

什么是方差和标准差&#xff1f; 方差(variance) 和标准差(standard variance) 方差&#xff1a;表示一组离散数据偏离平均值的程度。 公式&#xff1a; 方差公式 方差的算术平方根称为该随机变量的标准差。 在Matlab中&#xff0c;方差用var函数求&#xff0c;标准差用std函数…

matlab里方差分析的盒子图怎么看,Matlab方差分析

Matlab 方差分析(T检验) 在工农业生产和科学研究中,经常遇到这样的问题:影响产品产量、质量的因素很多,我们需要了解在这众多的因素中,哪些因素对影响产品产量、质量有显著影响.为此,要先做试验,然后对测试的结果进行分析.方差分析就是分析测试结果的一种方法.在方差分析中,把在…

20171205_Matlab求方差,均值,均方差,协方差的函数

1、 均值 数学定义&#xff1a; Matlab函数&#xff1a;mean >>X[1,2,3] >>mean(X)2 如果X是一个矩阵&#xff0c;则其均值是一个向量组。mean(X,1)为列向量的均值&#xff0c;mean(X,2)为行向量的均值。 >>X[12 3 45 6] >>mean(X,1)[2.5,3.5, 4.5] &g…

方差分析MATLAB实现

单因素方差分析的MATLAB实现 单因素均衡数据的实现 单因素非均衡数据方差分析 p192 8.22 X[85,80,90,88,87,94,56,62,55,48,92,99,95,91,75,72,81];group[ones(1,3),2*ones(1,4),3*ones(1,2),4*ones(1,2),5*ones(1,4),6*ones(1,3)];anova1(X,group); 从箱线图可以看到第2个第五…

matlab算方差std,MATLAB 方差函数 var std

1、均值 数学定义: Matlab函数:mean >>X=[1,2,3] >>mean(X)=2 如果X是一个矩阵,则其均值是一个向量组。mean(X,1)为列向量的均值,mean(X,2)为行向量的均值。 >>X=[1 2 3 4 5 6] >>mean(X,1)=[2.5, 3.5, 4.5] >>mean(X,2)=[2 5] 若要求整个矩…

matlab 方差,方差分解——matlab 代码

封面图片源自网络: 接着前面两期分析,今天介绍期限结构和收益率的方差分解代码: function var_plot= var_term( Phi_DRAW,OMIGA_ff_DRAW,HH) %%%% HH means the step length for forecast %%%%%%%%%% %%%%%% get the forecast variance decomposition %%%%%%% %%% SIGMA_u=P…

matlab u怎么求均方差,Matlab求方差,均值,均方差,協方差的函數

1、均值 數學定義&#xff1a; Matlab函數&#xff1a;mean >>X[1,2,3] >>mean(X)2 如果X是一個矩陣&#xff0c;則其均值是一個向量組。mean(X,1)為列向量的均值&#xff0c;mean(X,2)為行向量的均值。 >>X[1 2 3 4 5 6] >>mean(X,1)[2.5, 3.5, 4.5]…

Matlab系列教程_数值计算_求方差和标准差

首先&#xff0c;什么是方差和标准差&#xff1f; 方差&#xff0c;是在概率论和统计方差衡量随机变量或一组数据时离散程度的度量&#xff0c;统计中的方差&#xff08;样本方差&#xff09;是每个样本值与全体样本值的平均数之差的平方值的平均数。在许多实际问题中&#xff…

MATLAB中均值、方差、均方差的计算方法

1、 均值 数学定义&#xff1a; &#xff08;自己搜一下&#xff09; Matlab函数&#xff1a;mean >>X[1,2,3] >>mean(X)2 如果X是一个矩阵&#xff0c;则其均值是一个向量组。mean(X,1)为列向量的均值&#xff0c;mean(X,2)为行向量的均值。 >>X[1 2 3 4 5 …

利用MATLAB求均值、方差和标准差

1、 均值 数学定义&#xff1a; Matlab函数&#xff1a;mean 如果X是一个矩阵&#xff0c;则其均值是一个向量组。mean(X,1)为列向量的均值&#xff0c;mean(X,2)为行向量的均值。若要求整个矩阵的均值&#xff0c;则为mean(mean(X))或者mean2(X)。 2、 方差 数学定义&…

matlab 方差计算

代码如下&#xff1a; I imread(); dark_Idouble(I)/255; avgmean2(dark_I); %求图像均值 [m,n]size(dark_I); s0; for x1:mfor y1:nss(dark_I(x,y)-avg)^2; %求得所有像素与均值的平方和。end end%求图像的方差 a1var(dark_I(:)); %第一种方法&#xff1a;利用函数var求得…

环形队列的实现

首先我们先来了解一下队列是什么&#xff1f; 队列&#xff1a;数据先入先出&#xff0c;后进后出&#xff08;与栈刚好相反&#xff09;&#xff0c;主要通过数组实现。需要通过两个指针来创建对应的队列&#xff1b;一个指针为前缀pre&#xff0c;一个指针为后缀rear。pre指…

环形队列(Python代码实现)

环形队列是是在普通队列上进行的变化&#xff0c;本质和普通单向队列相同&#xff0c;都是队尾进队&#xff0c;队首出队。环形队列与普通队列的区别在于它能够循环利用空间&#xff0c;元素从队首出队后释放的空间能够被重复利用。 主要特点&#xff1a; 当队尾指针front M…