下面写了个对XML文档进行添、删、改、查的程序.
先是xml文档,代码如下:
<?xml version="1.0" encoding="utf-8"?><studentInfo>
<student>
<name id="100">aa</name>
<age>18</age>
<sex>男</sex>
<score>68</score>
</student>
<student>
<name id="101">bb</name>
<age>20</age>
<sex>女</sex>
<score>79</score>
</student>
<student>
<name id="102">cc</name>
<age>20</age>
<sex>女</sex>
<score>68</score>
</student>
</studentInfo>
然后就是java应用程序,注解已说明,首先要在外面下载个包"xerces.jar",(当然也可用Eclipse中自带的,只是代码稍稍不同)代码如下:
package com.Dome;
import java.io.BufferedReader;
import java.io.FileReader;
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.xerces.parsers.DOMParser;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
public class DomeTest {
/*
* 此方法为得到Document对象实例
*/
public static Document getInstance(String xmlPath) {
Document doc = null;
try {
BufferedReader bf = new BufferedReader(new FileReader(xmlPath));
DOMParser ps = new DOMParser();// xml解析器
ps.parse(new InputSource(bf));// 解析xml
doc = ps.getDocument();// 获得Document对象
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
/*
* 此方法用来打印元素等
*/
public static void printAll(Document doc) {
NodeList nl = doc.getElementsByTagName("*");
Node n;
for (int i = 0; i < nl.getLength(); i++) {
n = nl.item(i);
System.out.println(n.getNodeName() + " ");
}
}
/*
* 此方法用来打印属性
*/
public static void printAttr(Document doc) {
NodeList nl = doc.getElementsByTagName("*");
Element e;
Attr att;// 属性对象
NamedNodeMap nnm;// 属性对象集合
String attrname;
String attrval;
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
System.out.println(e.getTagName() + ":"
+ e.getFirstChild().getNodeValue());
nnm = e.getAttributes();
if (nnm != null) {
for (int j = 0; j < nnm.getLength(); j++) {
att = (Attr) nnm.item(j);
attrname = att.getName();
attrval = att.getValue();
System.out.println("属性是:" + attrname + "=" + attrval);
}
}
}
}
/*