java 解析 xml (DOM方法全)

时间:2023-11-30 11:04:02

Java 处理 XML 的三种主流技术及介绍 http://www.ibm.com/developerworks/cn/xml/dm-1208gub/

这篇文章讲的比较详细,下面我主要介绍 dom方法 对xml文件的增删改操作。

参见http://blog.csdn.net/smcwwh/article/details/7183869 但由于排版有点乱,我整理下我需要的,作为以后的笔记吧。。。

DOM 最大的特点是:实现 W3C 标准,有多种编程语言支持这种解析方式,并且这种方法本身操作上简单快捷,十分易于初学者掌握。其处理方式是将 XML 整个作为类似树结构的方式读入内存中以便操作及解析,因此支持应用程序对 XML 数据的内容和结构进行修改,但是同时由于其需要在处理开始时将整个 XML 文件读入到内存中去进行分析,因此其在解析大数据量的 XML 文件时会遇到类似于内存泄露以及程序崩溃的风险,请对这点多加注意。

适用范围:小型 XML 文件解析、需要全解析或者大部分解析 XML、需要修改 XML 树内容以生成自己的对象模型

下文代码用到的xml数据源

<?xml version="1.0" encoding="UTF-8"?>
<university name="pku">
<college name="c1">
<class name="class1">
<student name="stu1" sex='male' age="21" />
<student name="stu2" sex='female' age="20" />
<student name="stu3" sex='female' age="20" />
</class>
<class name="class2">
<student name="stu4" sex='male' age="19" />
<student name="stu5" sex='female' age="20" />
<student name="stu6" sex='female' age="21" />
</class>
</college>
<college name="c2">
<class name="class3">
<student name="stu7" sex='male' age="20" />
</class>
</college>
<college name="c3">
</college>
</university>

读文件

 public static void read() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");//文件名
Document doc = builder.parse(in);
// root <university>
Element root = doc.getDocumentElement();
if (root == null) return;
System.err.println(root.getAttribute("name"));
// all college node
NodeList collegeNodes = root.getChildNodes();
if (collegeNodes == null) return;
for(int i = 0; i < collegeNodes.getLength(); i++) {
Node college = collegeNodes.item(i);
if (college != null && college.getNodeType() == Node.ELEMENT_NODE) {
System.err.println("\t" + college.getAttributes().getNamedItem("name").getNodeValue());
// all class node
NodeList classNodes = college.getChildNodes();
if (classNodes == null) continue;
for (int j = 0; j < classNodes.getLength(); j++) {
Node clazz = classNodes.item(j);
if (clazz != null && clazz.getNodeType() == Node.ELEMENT_NODE) {
System.err.println("\t\t" + clazz.getAttributes().getNamedItem("name").getNodeValue());
// all student node
NodeList studentNodes = clazz.getChildNodes();
if (studentNodes == null) continue;
for (int k = 0; k < studentNodes.getLength(); k++) {
Node student = studentNodes.item(k);
if (student != null && student.getNodeType() == Node.ELEMENT_NODE) {
System.err.print("\t\t\t" + student.getAttributes().getNamedItem("name").getNodeValue());
System.err.print(" " + student.getAttributes().getNamedItem("sex").getNodeValue());
System.err.println(" " + student.getAttributes().getNamedItem("age").getNodeValue());
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }

修改节点并将其写入文件

   public static void write() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");
Document doc = builder.parse(in);
// root <university>
Element root = doc.getDocumentElement();
if (root == null) return;
// 修改属性
root.setAttribute("name", "tsu");
NodeList collegeNodes = root.getChildNodes();
if (collegeNodes != null) {
for (int i = 0; i <collegeNodes.getLength() - 1; i++) {
// 删除节点
Node college = collegeNodes.item(i);
if (college.getNodeType() == Node.ELEMENT_NODE) {
String collegeName = college.getAttributes().getNamedItem("name").getNodeValue();
if ("c1".equals(collegeName) || "c2".equals(collegeName)) {
root.removeChild(college);
} else if ("c3".equals(collegeName)) {
Element newChild = doc.createElement("class");
newChild.setAttribute("name", "c4");
college.appendChild(newChild);
}
}
}
}
// 新增节点
Element addCollege = doc.createElement("college");
addCollege.setAttribute("name", "c5");
root.appendChild(addCollege);
Text text = doc.createTextNode("text");
addCollege.appendChild(text); // 将修改后的文档保存到文件
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transFormer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
File file = new File("src/dom-modify.xml");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
StreamResult xmlResult = new StreamResult(out);
transFormer.transform(domSource, xmlResult);
System.out.println(file.getAbsolutePath());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}