先是xml文檔
<?xml version=
<student>
<name id=
<age>
<sex>男</sex>
<score>
</student>
<student>
<name id=
<age>
<sex>女</sex>
<score>
</student>
<student>
<name id=
<age>
<sex>女</sex>
<score>
</student>
</studentInfo>
然後就是java應用程序
package com
import java
import java
import javax
import javax
import javax
import javax
import org
import org
import org
import org
import org
import org
import org
import org
import org
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
doc = ps
} catch (Exception e) {
e
}
return doc;
}
/*
* 此方法用來打印元素等
*/
public static void printAll(Document doc) {
NodeList nl = doc
Node n;
for (int i =
n = em(i);
System
}
}
/*
* 此方法用來打印屬性
*/
public static void printAttr(Document doc) {
NodeList nl = doc
Element e;
Attr att;// 屬性對象
NamedNodeMap nnm;// 屬性對象集合
String attrname;
String attrval;
for (int i =
e = (Element) em(i);
System
+ e
nnm = e
if (nnm != null) {
for (int j =
att = (Attr) em(j);
attrname = att
attrval = att
System
}
}
}
}
/*
* 此為添加方法 */
public static void addElement(Document dc) {
Element estu = dc
Element ename = dc
Element esex = dc
Element eage = dc
Element escore = dc
Text tname = dc
Text tsex = dc
Text tage = dc
Text tscore = dc
estu
estu
estu
estu
dc
}
/*
* 此為修改方法
*/
public static void updateElement(Document dc
NodeList nl = dc
Element e;
for (int i =
e = (Element) em(i);
if (e
Node n = e
NodeList nd = n
for (int j =
Node node = em(j);
if (node
node
}
}
}
}
}
/*
* 此方法為刪除方法
*/
public static void delElement(Document dc
NodeList nl=dc
Element e;
NamedNodeMap nnm;//屬性集合
Attr att;
for(int i=
e=(Element)em(i);
nnm=e
if(nnm!=null){
for(int j=
att=(Attr)em(j);
if((att
(e
}
}
}
}
}
/*
* 此方法把在程序中所做的操作保存於xml文檔中
*/
public static void saveXml(Document dom) {
TransformerFactory tff = TransformerFactory
try {
Transformer tf = tff
tf
tf
} catch (Exception e) {
e
}
}
/**
* main方法
*/
public static void main(String[] args) {
Document dc = getInstance(
// printAll(dc);
// addElement(dc);
//updateElement(dc
delElement(dc
saveXml(dc);
printAttr(dc);
}
}
From:http://tw.wingwit.com/Article/program/net/201311/11853.html