1.DOM介绍
DOM 是用与平台和语言无关的方式表示XML文档的官方 W3C 标准。DOM 是以层次结构组织的节点或信息片断的集合。这个层次结构允许开发人员在树中寻找特定信息。分析该结构通常需要加载整个文档和构造层次结构, 然后才能做任何工作。 由于它是基于信息层次的,因而 DOM 被认为是基于树或基于对象的。DOM 以及广义的基于树的处理具有几个优点。首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改。 它还可以在任何时候在树中上下导航, 而不是像 SAX 那样是一次性的处理。 DOM使用起来也要简单得多。
2.采用DOM解析XML文件
代码实例:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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:胡家威 * @CreateTime:2011-9-6 下午10:12:00 * @Description:采用DOM解析XML文件 */ public class DomXML { public void domXMl(String fileName) { try { DocumentBuilder domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputStream input = new FileInputStream(fileName); Document doc = domBuilder.parse(input); Element root = doc.getDocumentElement(); NodeList students = root.getChildNodes(); if (students != null) { for (int i = 0, size = students.getLength(); i < size; i++) { Node student = students.item(i); if (student.getNodeType() == Node.ELEMENT_NODE) { String sexString = student.getAttributes().getNamedItem("性别").getNodeValue(); System.out.println(sexString); } for (Node node = student.getFirstChild(); node != null; node = node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("姓名")) { String name = node.getFirstChild().getNodeValue(); System.out.println(name); } if (node.getNodeName().equals("年龄")) { String age = node.getFirstChild().getNodeValue(); System.out.println(age); } if (node.getNodeName().equals("电话")) { String tel = node.getFirstChild().getNodeValue(); System.out.println(tel); } } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { DomXML xmlTest = new DomXML(); String fileName = "students.xml"; xmlTest.domXMl(fileName); } }
目录结构:在项目的根目录下面放置一个XML文件
<? xml version = "1.0" encoding = "UTF-8" ?> |
<学生花名册> |
<学生 性别="男"> |
<姓名>李华</姓名> |
<年龄>14</年龄> |
<电话>6287555</电话> |
</学生> |
<学生 性别="男"> |
<姓名>张三</姓名> |
<年龄>16</年龄> |
<电话>8273425</电话> |
</学生> |
</学生花名册> |
运行结果:
男
李华
14
6287555
男
张三
16
8273425
3.使用DOM操作XML文件,进行增删查改
代码示例:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
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:胡家威
* @CreateTime:2011-9-23 下午09:08:03
* @Description:DOM操作XML文件,增删查改
*/
public class DealXML {
public static void main(String[] args) {
try {
// Document-->Node
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( "products.xml");
Element root = document.getDocumentElement();
// 增加一个元素节点
Element newChild = document.createElement( "project");
newChild.setAttribute( "id", "NP001"); // 添加id属性
Element nelement = document.createElement( "name"); // 元素节点
nelement.setTextContent( "New Project");
newChild.appendChild(nelement);
Element selement = document.createElement( "start-date");
selement.setTextContent( "March 20 1999");
newChild.appendChild(selement);
Element eelement = document.createElement( "end-date");
eelement.setTextContent( "July 30 2004");
newChild.appendChild(eelement);
root.appendChild(newChild);
// 查找一个元素节点
String expression = "/projects/project[3]";
Element node = (Element) selectSingleNode(expression, root); // 转型一下
// 修改一个元素节点
node.getAttributeNode( "id").setNodeValue( "new " +node.getAttribute( "id"));
// root.getElementsByTagName("project").item(2).setTextContent("");
expression = "/projects/project";
NodeList nodeList = selectNodes(expression, root);
nodeList.item( 1).getAttributes().getNamedItem( "id").setNodeValue( "New Id");
// 删除一个元素节点
expression = "/projects/project[2]";
node = (Element) selectSingleNode(expression, root);
root.removeChild(root.getFirstChild());
output(root, "newProjects.xml");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
public static void output(Node node, String filename) {
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
// 设置各种输出属性
transformer.setOutputProperty( "encoding", "gb2312");
transformer.setOutputProperty( "indent", "yes");
DOMSource source = new DOMSource();
// 将待转换输出节点赋值给DOM源模型的持有者(holder)
source.setNode(node);
StreamResult result = new StreamResult();
if (filename == null) {
// 设置标准输出流为transformer的底层输出目标
result.setOutputStream(System.out);
} else {
result.setOutputStream( new FileOutputStream(filename));
}
// 执行转换从源模型到控制台输出流
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 查找一个单独的节点
private static Node selectSingleNode(String expression, Object source) {
try {
return (Node) XPathFactory.newInstance().newXPath().evaluate(expression, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
// 查找所有的节点
private static NodeList selectNodes(String expression, Object source) {
try {
return (NodeList) XPathFactory.newInstance().newXPath().evaluate(expression, source, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
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:胡家威
* @CreateTime:2011-9-23 下午09:08:03
* @Description:DOM操作XML文件,增删查改
*/
public class DealXML {
public static void main(String[] args) {
try {
// Document-->Node
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( "products.xml");
Element root = document.getDocumentElement();
// 增加一个元素节点
Element newChild = document.createElement( "project");
newChild.setAttribute( "id", "NP001"); // 添加id属性
Element nelement = document.createElement( "name"); // 元素节点
nelement.setTextContent( "New Project");
newChild.appendChild(nelement);
Element selement = document.createElement( "start-date");
selement.setTextContent( "March 20 1999");
newChild.appendChild(selement);
Element eelement = document.createElement( "end-date");
eelement.setTextContent( "July 30 2004");
newChild.appendChild(eelement);
root.appendChild(newChild);
// 查找一个元素节点
String expression = "/projects/project[3]";
Element node = (Element) selectSingleNode(expression, root); // 转型一下
// 修改一个元素节点
node.getAttributeNode( "id").setNodeValue( "new " +node.getAttribute( "id"));
// root.getElementsByTagName("project").item(2).setTextContent("");
expression = "/projects/project";
NodeList nodeList = selectNodes(expression, root);
nodeList.item( 1).getAttributes().getNamedItem( "id").setNodeValue( "New Id");
// 删除一个元素节点
expression = "/projects/project[2]";
node = (Element) selectSingleNode(expression, root);
root.removeChild(root.getFirstChild());
output(root, "newProjects.xml");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
public static void output(Node node, String filename) {
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
// 设置各种输出属性
transformer.setOutputProperty( "encoding", "gb2312");
transformer.setOutputProperty( "indent", "yes");
DOMSource source = new DOMSource();
// 将待转换输出节点赋值给DOM源模型的持有者(holder)
source.setNode(node);
StreamResult result = new StreamResult();
if (filename == null) {
// 设置标准输出流为transformer的底层输出目标
result.setOutputStream(System.out);
} else {
result.setOutputStream( new FileOutputStream(filename));
}
// 执行转换从源模型到控制台输出流
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 查找一个单独的节点
private static Node selectSingleNode(String expression, Object source) {
try {
return (Node) XPathFactory.newInstance().newXPath().evaluate(expression, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
// 查找所有的节点
private static NodeList selectNodes(String expression, Object source) {
try {
return (NodeList) XPathFactory.newInstance().newXPath().evaluate(expression, source, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
}
左边是修改前的,右边的是修改了之后生成的XML文件