四、用例:
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());
}
}
}
分享到:
相关推荐
本篇文档《JDOM使用详解及实例(解析xml).pdf》将对JDOM的使用方法进行详细介绍,并提供实例来指导用户如何解析XML。 首先,JDOM提供了一种基于对象的XML表示方式。与DOM(文档对象模型)不同,JDOM不需要将XML文档...
JDOM 是一个专门为Java设计的XML处理库,它结合了SAX和DOM的优点,提供了一种高效且易于使用的API来创建、解析和操作XML文档。JDOM的主要目标是简化XML处理,通过利用Java语言的强大特性,如方法重载、集合和映射,...
**二、JDOM包结构** JDOM主要包含以下几个包: 1. `org.jdom`: 包含所有XML文档元素的Java类。 2. `org.jdom.adapters`: 提供与DOM的适配器类。 3. `org.jdom.filter`: 提供XML文档过滤器类。 4. `org.jdom.input`: ...
JDOM 在2000年的春天被Brett McLaughlin和Jason Hunter开发出来,以弥补DOM及SAX在实际应用当中的不足之处。 这些不足之处主要在于SAX没有文档修改、随机访问以及输出的功能,而对于DOM来说,JAVA程序员在使用时来...
**JDOM库详解** 在Java开发中,XML(可扩展标记语言)被广泛用于数据交换、配置存储等场景。为了方便地处理XML文档,Java提供了多种解析器,其中之一就是JDOM(Java Document Object Model)。本篇文章将深入探讨...
**JDOM驱动包详解** JDOM,全称为Java Document Object Model,是一个专为Java设计的XML处理库。它提供了一种高效、灵活且方便的方式来创建、解析和操作XML文档。在Java开发中,JDOM是处理XML数据的一种常用工具,...
**JDom详解** 1. **JDom简介** JDom是Java Document Object Model的简称,它是基于Java语言的一个XML处理库。相比于DOM(Document Object Model)API,JDom更专注于Java平台,提供了更加直观和高效的API设计,减少...
6.2.2 实例二:welcomeyou 210 6.2.3 实例三:outputinfo 216 6.2.4 实例四:loginservlet 220 6.3 servlet异常 223 6.3.1 servletexception类 224 6.3.2 unavailableexception类 224 6.4 servlet生命周期 224...
例如,可以使用`DocumentBuilderFactory`和`DocumentBuilder`创建一个`Document`实例,然后添加`Element`,再添加子元素和属性。 4. **解析XML文档**:JDOM提供了`SAXBuilder`类来解析XML文件,将其转换为JDOM对象...
6.2.2 实例二:welcomeyou 210 6.2.3 实例三:outputinfo 216 6.2.4 实例四:loginservlet 220 6.3 servlet异常 223 6.3.1 servletexception类 224 6.3.2 unavailableexception类 224 6.4 servlet生命周期 224...
**JDOM API中文详解** JDOM,全称Java Document Object Model,是一个专为Java设计的XML处理库。它提供了一种高效、灵活且方便的方式来创建、读取、修改和保存XML文档。JDOM API是Java程序员操作XML文档的核心工具...
### DOM、JDOM、DOM4J解析XML实例详解 #### DOM 方式解析 XML 实例解析 ##### 一、DOM 概述与应用实例 DOM(Document Object Model)是一种树状结构的标准,用于表示 XML 文档的数据结构。它将 XML 文档视为节点...
**JDOM SAXBuilder详解** JDOM,全称Java Document Object Model,是一个用于处理XML文档的Java库。它提供了一个纯Java的解决方案来创建、修改和读取XML文档,旨在提高性能和易用性。SAXBuilder是JDOM库中的一个...
### jdom4j解析XML实例详解 #### 生成XML文档 在示例代码中,`generateXML`方法用于创建一个XML文档。首先,通过`DocumentHelper.createDocument()`调用创建了一个空白的`Document`对象,这相当于创建了一个XML文件...
6.2.2 实例二:welcomeyou 210 6.2.3 实例三:outputinfo 216 6.2.4 实例四:loginservlet 220 6.3 servlet异常 223 6.3.1 servletexception类 224 6.3.2 unavailableexception类 224 6.4 servlet生命周期 224...
6.2.2 实例二:welcomeyou 210 6.2.3 实例三:outputinfo 216 6.2.4 实例四:loginservlet 220 6.3 servlet异常 223 6.3.1 servletexception类 224 6.3.2 unavailableexception类 224 6.4 servlet生命周期 224...
**JDOM解析模型详解** Java开发中,XML(Extensible Markup Language)作为一种数据交换和存储格式,被广泛应用在各种系统间的数据传输与配置文件中。为了处理XML文档,Java提供了多种解析器,其中之一就是JDOM。...
《JDOM与SAX解析XML文件详解》 在Java编程领域,处理XML文件是一项常见的任务。XML(eXtensible Markup Language)作为一种可扩展标记语言,广泛用于数据交换、配置存储以及文档结构化等场景。本文将深入探讨如何...
**JDOM 操作 XML 文档详解** XML (eXtensible Markup Language) 是一种用于标记数据的语言,广泛应用于数据交换、配置文件等场景。而 JDOM(Java Document Object Model)是一个专门为 Java 设计的 XML 处理库,它...