四、用例:
StudentInfo
/**
* JDomSample
*/
package com.fhway.jdom;
/**
* @author fuhw
* 2006-9-19 下午05:15:00
*/
public class StudentInfo {
private String number = "";
private String name = "";
private String age = "";
private String familialMembers = "";
private String fatherName = "";
private String motherName = "";
/**
* @return the age
*/
public String getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(String age) {
this.age = age;
}
/**
* @return the familialMembers
*/
public String getFamilialMembers() {
return familialMembers;
}
/**
* @param familialMembers the familialMembers to set
*/
public void setFamilialMembers(String familialMembers) {
this.familialMembers = familialMembers;
}
/**
* @return the fatherName
*/
public String getFatherName() {
return fatherName;
}
/**
* @param fatherName the fatherName to set
*/
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
/**
* @return the motherName
*/
public String getMotherName() {
return motherName;
}
/**
* @param motherName the motherName to set
*/
public void setMotherName(String motherName) {
this.motherName = motherName;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the number
*/
public String getNumber() {
return number;
}
/**
* @param number the number to set
*/
public void setNumber(String number) {
this.number = number;
}
}
JDomSample
/**
* JDomSample
*/
package com.fhway.jdom;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
/**
* @author fuhw 2006-9-13 下午04:44:21
*/
public class JDomSample {
public static void build(String filePath, StudentInfo si) throws Exception {
Element root, student, number, name, age, familialMembers, fatherName, motherName;
/* 生成根元素:student-info */
root = new Element("student-info");
/* 将根元素植入文档doc中 */
Document doc = new Document(root);
/* 生成元素:student(number,name,age) */
student = new Element("student");
number = new Element("number");
name = new Element("name");
age = new Element("age");
/* 生成familialMembers元素的子元素fatherName,materName */
familialMembers = new Element("familialMembers");
fatherName = new Element("fatherName");
motherName = new Element("motherName");
/* 设置属性的值 */
number.setText(si.getNumber());
name.setText(si.getName());
age.setText(si.getAge());
fatherName.setText(si.getFatherName());
motherName.setText(si.getMotherName());
/* 设置元素的节点内容 */
student.addContent(number);
student.addContent(name);
student.addContent(age);
/* 把fatherName,materName放在familialMembers下面 */
familialMembers.addContent(fatherName);
familialMembers.addContent(motherName);
/* 把familialMembers放在student下面 */
student.addContent(familialMembers);
root.addContent(student);
Format format = Format.getCompactFormat();
/* 设置xml文件的字符为gb2312 */
format.setEncoding("gb2312");
/* 设置xml文件的缩进为4个空格 */
format.setIndent(" ");
/* 元素后换行一层元素缩四格 */
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(doc, new FileOutputStream(filePath));
}
/**
* 添加XML文件指定信息
*/
public static void add(String filePath, StudentInfo si) throws Exception {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
String path = filePath;
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
/* 得到根元素 */
Element root = doc.getRootElement();
/* 得到根元素所有子元素的集合 */
List sis = root.getChildren();
String number = si.getNumber();
String name = si.getName();
String age = si.getAge();
// String familialMembers = si.getFamilialMembers();
String fatherName = si.getFatherName();
String motherName = si.getMotherName();
Element newstudent = new Element("student");
Element newnumber = new Element("number");
newnumber.setText(number);
newstudent.addContent(newnumber);
Element newname = new Element("name");
newname.setText(name);
newstudent.addContent(newname);
Element newage = new Element("age");
newage.setText(age);
newstudent.addContent(newage);
Element familialMembers = new Element("familialMembers");
Element newfatherName = new Element("fatherName");
newfatherName.setText(fatherName);
familialMembers.addContent(newfatherName);
Element newmotherName = new Element("motherName");
newmotherName.setText(motherName);
familialMembers.addContent(newmotherName);
newstudent.addContent(familialMembers);
sis.add(newstudent);// 增加子元素
Format format = Format.getCompactFormat();
/* 设置xml文件的字符为gb2312 */
format.setEncoding("gb2312");
/* 设置xml文件的缩进为4个空格 */
format.setIndent(" ");
/* 元素后换行一层元素缩四格 */
XMLOutputter outp = new XMLOutputter(format);
fo = new FileOutputStream(path);
outp.output(doc, fo);
System.out.println("AddXML is over!");
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void read(String filePath) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder();
try {
Document read_doc = builder.build(filePath);
/* root */
Element stu = read_doc.getRootElement();
List list = stu.getChildren("student");
for (int i = 0; i < list.size(); i++) {
Element e = (Element) list.get(i);
String str_number = e.getChildText("number");
String str_name = e.getChildText("name");
String str_age = e.getChildText("age");
/* 取得student元素的子节点元素familialMembers */
Element f = (Element) e.getChild("familialMembers");
String str_fatherName = f.getChildText("fatherName");
System.out.println("---------STUDENT--------------");
System.out.println("NUMBER:" + str_number);
System.out.println("NAME:" + str_name);
System.out.println("AGE:" + str_age);
System.out.println("fatherName:" + str_fatherName);
System.out.println("------------------------------");
System.out.println();
}
} catch (IOException ex) {
System.out.println("IOException" + ex.getMessage());
} catch (JDOMException je) {
System.out.println("JDOMException" + je.getMessage());
}
}
/**
* 修改XML文件指定信息
*/
public static void edit(String filePath, StudentInfo si) throws Exception {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
String path = filePath;
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement(); // 得到根元素
List list = root.getChildren(); // 得到根元素所有子元素的集合
Element student = (Element) list.get(0);
String number = si.getNumber();
String name = si.getName();
String age = si.getAge();
// String familialMembers = si.getFamilialMembers();
String fatherName = si.getFatherName();
String motherName = si.getMotherName();
System.out.println("fatherName:" + fatherName);
Element newnumber = student.getChild("number");
newnumber.setText(number);
Element newname = student.getChild("name");
newname.setText(name);
Element newage = student.getChild("age");
newage.setText(age);
Element newfamilialMembers = student.getChild("familialMembers");
Element newfatherName = (Element) newfamilialMembers
.getChild("fatherName");
newfatherName.setText(fatherName);
Element newmotherName = (Element) newfamilialMembers
.getChild("motherName");
newmotherName.setText(motherName);
XMLOutputter outp = new XMLOutputter();
fo = new FileOutputStream(path);
outp.output(doc, fo);
System.out.println("EditXML is over!");
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 删除XML文件指定信息
*/
public static void remove(String filePath, int xmlId) throws Exception {
FileInputStream fi = null;
FileOutputStream fo = null;
/* 类型转换 */
String path = filePath;
try {
fi = new FileInputStream(path);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
/* 得到根元素 */
Element root = doc.getRootElement();
/* 得到根元素所有子元素的集合 */
List sis = root.getChildren();
/* 删除指定位置的子元素 */
sis.remove(xmlId);
XMLOutputter outp = new XMLOutputter();
fo = new FileOutputStream(path);
outp.output(doc, fo);
System.out.println("DelXML is over!");
} catch (Exception e) {
System.err.println(e + "error");
} finally {
try {
fi.close();
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void xpathReader(String filePath) throws IOException,
JDOMException {
PrintStream out = System.out;
SAXBuilder builder = new SAXBuilder();
try {
/* 得到Document对象 */
Document doc = builder.build(new File(filePath));
// Print servlet information
/* 选择任意路径下servlet元素 */
XPath servletPath = XPath.newInstance("//servlet");
/* 返回所有的servlet元素 */
List servlets = servletPath.selectNodes(doc);
out.println("This WAR has " + servlets.size()
+ " registered servlets:");
Iterator i = servlets.iterator();
/* 输出servlet信息 */
while (i.hasNext()) {
Element servlet = (Element) i.next();
out.print("\t" + servlet.getChild("servlet-name").getTextTrim()
+ " for "
+ servlet.getChild("servlet-class").getTextTrim());
List initParams = servlet.getChildren("init-param");
out.println(" (it has " + initParams.size() + " init params)");
}
// Print security role information
XPath rolePath = XPath
.newInstance("//security-role/role-name/text()");
List roleNames = rolePath.selectNodes(doc);// 得到所有的角色名
if (roleNames.size() == 0) {
out.println("This WAR contains no roles");
} else {
out
.println("This WAR contains " + roleNames.size()
+ " roles:");
i = roleNames.iterator();
while (i.hasNext()) {// 输出角色名
out.println("\t" + ((Text) i.next()).getTextTrim());
}
}
} catch (IOException ioe) {
System.out.println(ioe.getStackTrace());
} catch (JDOMException jde) {
System.out.println(jde.getStackTrace());
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String filePath = "";
StudentInfo si = new StudentInfo();
si.setNumber("011");
si.setName("fhwei");
si.setAge("27");
si.setFatherName("myFather");
si.setMotherName("myMother");
/* 读取文件的的路径 */
if (args.length == 2) {
filePath = args[1];
} else {
filePath = "studentInfo.xml";
}
try{
// build(filePath, si);
// read(filePath);
// edit(filePath, si);
// read(filePath);
xpathReader("web.xml");
}catch(Exception e){
System.out.println(e.getStackTrace());
}
}
}