DOM 创建 解析 读取 转换 XML
package com.itheima.xml;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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.NodeList;
import org.w3c.dom.Text;
import com.itheima.xml.bean.Employee;
public class TextDOMParseXML {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String inFileName="F:/poem.xml";
String outFileName="F:/poem1.xml";
try {
List employees=TextDOMParseXML.readXMLFile(inFileName);
System.out.println("输出到控制台的XML文档!");
System.out.println("文件(包括路径和后缀名):"+TextDOMParseXML.writeXMLFile(outFileName, employees));
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
public static List readXMLFile(String fileName){
//获取dom解析器的工厂实例
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder build=null;
try {
build=dbf.newDocumentBuilder(); //从DOM 工厂中获取dom解析器
} catch (Exception e) {
// TODO: handle exception
System.out.println("获取dom解析器失败:"+e.getMessage());
return null;
}
Document doc=null;
try {
doc=build.parse(fileName); //解析XML文档的对象
doc.normalize();// 去掉XML文档中格式化文档内容空白
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
return null;
}
List employees=new ArrayList(); //创建列表
Employee employee=null;
Element root=doc.getDocumentElement(); //得到XML文档的节点
NodeList nodeList=root.getElementsByTagName("employee");
for(int i=0;i<nodeList.getLength();i++){
Element element=(Element)nodeList.item(i);
employee=new Employee();
employee.setEid(element.getAttribute("id"));
employee.setGender(element.getAttribute("gender"));
NodeList names=element.getElementsByTagName("name");
if(names.getLength()==1){
Element e=(Element)names.item(0);
Text t=(Text)e.getFirstChild();
employee.setName(t.getNodeValue());
}
NodeList ages=element.getElementsByTagName("age");
if(ages.getLength()==1){
Element e=(Element)ages.item(0);
Text t=(Text)e.getFirstChild();
employee.setAge(Integer.parseInt(t.getNodeValue()));
}
NodeList address=element.getElementsByTagName("address");
if(address.getLength()==1){
Element e=(Element)address.item(0);
Text t=(Text)e.getFirstChild();
employee.setAddress(t.getNodeValue());
}
employees.add(employee);
}
return employees;
}
//把 DOM写成XML文档 ,把学生信息以XML文档形式存储
public static String writeXMLFile(String outFile,List employees) throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
try {
db=dbf.newDocumentBuilder();
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
Document doc=null;
doc=db.newDocument();
//建立根节点元素
Element root=doc.createElement("employees");
doc.appendChild(root); //添加根节点元素
for (int i = 0; i < employees.size(); i++) {
Employee employee=(Employee)employees.get(i);
Element element=doc.createElement("employee");
element.setAttribute("id", employee.getEid());
element.setAttribute("gender", employee.getGender());
root.appendChild(element);
Element name =doc.createElement("name");
name.setTextContent("jj");
Text tName=doc.createTextNode(employee.getName());
name.appendChild(tName);
element.appendChild(name);
Element age=doc.createElement("age");
Text tAge=doc.createTextNode(String.valueOf(employee.getAge()));
age.appendChild(tAge);
element.appendChild(age);
Element address=doc.createElement("address");
Text tAddress=doc.createTextNode(employee.getAddress());
address.appendChild(tAddress);
element.appendChild(address);
}
return domDocToFile(doc,outFile,"GB2312");
}
//使用JAXP 将Dom写到XML文档里
private static String domDocToFile(Document doc, String fileName,
String encoding) throws TransformerException {
//为了得到XSLT对象引擎
TransformerFactory factory=TransformerFactory.newInstance();
Transformer transformer=factory.newTransformer();
Properties properties=transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, encoding);
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.INDENT, "yes"); //设置是否缩进
transformer.setOutputProperties(properties);
DOMSource source=new DOMSource(doc);
File file=new File(fileName);
StreamResult result=new StreamResult(file);
StreamResult result1=new StreamResult(System.out);
transformer.transform(source, result); //执行 DOM 文档到 XML文档转换
transformer.transform(source, result1); //执行DOM 输出到控制台
System.out.println();
return file.getAbsolutePath(); //输出文件的路径
}
}