使用DOM对XML文档进行创建和解析
程序员文章站
2022-05-28 14:47:58
...
使用DOM来创建和解析XML文档,参考网站:www.51cto.com
我们以以下的xml文档为例:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees>
<employee>
<name>Voishion</name>
<sex>M</sex>
<age>23</age>
</employee>
</employees>
首先定义一个行为规范的接口:
package com.pb.viewer.xml;
/**
* 定义XML文件的建立与解析
* @author Voishion
* @version 2012.12.28
*/
public interface XMLDocument {
/**
* 建立XML文档
* @param fileName
*/
public void createXML(String fileName);
/**
* 解析XML文档
* @param fileName
*/
public void parserXML(String fileName);
}
下面是接口的实现,需要注意的是我们一般创建的xml文件都在项目的src文件目录下:
package com.pb.viewer.xml;
import java.io.File;
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.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
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;
/**
* DOM生成与解析XML文档实现
* @author Voishion
* @date 2012.12.28
*/
public class XMLDocumentImpl implements XMLDocument{
private static Logger log = Logger.getLogger(XMLDocumentImpl.class);
private DocumentBuilder builder;
private Document document;
public XMLDocumentImpl(){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
this.builder = dbf.newDocumentBuilder();
this.document = this.builder.newDocument();
} catch (ParserConfigurationException e) {
log.error(e.getMessage());
}
}
/**
* 解析指定文件名的XML文件
*/
@Override
public void parserXML(String fileName) {
try {
Document document = this.builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName));
NodeList employess = document.getChildNodes();
for(int i = 0; i < employess.getLength(); i++){
Node employee = employess.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());
}
}
}
log.fatal("解析"+fileName+"完毕!");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 创建指定文件名的XML文件
*/
@Override
public void createXML(String fileName) {
Element root = this.document.createElement("employees");
this.document.appendChild(root);
//employee Tag
Element employee = this.document.createElement("employee");
//name Tag
Element name = this.document.createElement("name");
name.appendChild(this.document.createTextNode("Voishion"));
employee.appendChild(name);
//sex Tag
Element sex = this.document.createElement("sex");
sex.appendChild(this.document.createTextNode("M"));
employee.appendChild(sex);
//age Tag
Element age = this.document.createElement("age");
age.appendChild(this.document.createTextNode("23"));
employee.appendChild(age);
//employee Tag Add root Tag
root.appendChild(employee);
TransformerFactory tf = TransformerFactory.newInstance();
try{
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
File file = new File(new File(".\\src").getCanonicalPath()+"\\"+fileName);
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
log.fatal(fileName + "生成XML文件成功!");
}catch (Exception e) {
log.error(e.getMessage());
}
}
}
下面是测试类,需要注意的是当创建xml文件完成以后要对整个项目都刷新一次,才能看见创建到的xml文件:
package com.pb.viewer.xml;
public class XMLTest {
XMLDocument document;
public void createDOMXML(){
document = new XMLDocumentImpl();
document.createXML("employee.xml");
}
public void parserDOMXML(){
document = new XMLDocumentImpl();
document.parserXML("employee.xml");
}
/**
* @param args
*/
public static void main(String[] args) {
XMLTest test = new XMLTest();
test.createDOMXML();
// test.parserDOMXML();
}
}
至此基于DOM的xml文件的创建与解析已全部完成,欢迎提出升级意见,TKS
转载于:https://my.oschina.net/lilu/blog/99083