对xml文档的解析java中有很多种方法,例如使用dom、sax、jdom等等,相比之下,我觉得还是jdom比较方便。下面介绍一下jdom的基本使用方法,不对之处还请各位网友之交。谢谢!
最新的jdom可以到他的网站:http://www.jdom.org/去下载,现在的版本是1.0版,下载之后将得到jdom-1.0.zip文件,解压后进入build文件夹将看到一个名为jdom.jar的包,这个就是jdom的类包了,将它加到你的classpath里就可以使用jdom提供的各种处理xml的类和他们的方法了。应该注意的是在解压后的文件夹里还有一个lib文件夹,里面保存的是使用jdom的环境包,不过我在我的jdk1.4下使用没引用这些包一样好用,不知道是jdk1.4中已经包含了这些东西还是原来我的eclipse已经引用了这些包,呵呵。
好了,书归正传,现在开始介绍jdom包的使用。
jdom包的结构包括:
org.jdom 包含了所有的xml文档要素的java类
org.jdom.adapters 包含了与dom适配的java类
org.jdom.filter 包含了xml文档的过滤器类
org.jdom.input 包含了读取xml文档的类
org.jdom.output 包含了写入xml文档的雷
org.jdom.transform 包含了将jdom xml文档接口转换为其他xml文档接口
org.jdom.xpath 包含了对xml文档xpath操作的类
下面将通过一个例子介绍jdom的常用操作
生成xml文档:
下面的类将生成一个xml文档:
/*
* Created on 2004-10-9
*
* 写入xml文件的例子
*/
/**
* @author lnman
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import java.io.*;
import org.jdom.*;
import org.jdom.output.*;
public class WriteXML
{
public void BuildXML() throws Exception
{
Element root,student,number,name,age;
root = new Element("student-info"); //生成根元素:student-info
student = new Element("student"); //生成元素:student,该元素中将包含元素number,name,age
number = new Element("number");
name = new Element("name");
age = new Element("age");
Document doc = new Document(root); //将根元素植入文档doc中
number.setText("001");
name.setText("lnman");
age.setText("24");
student.addContent(number);
student.addContent(name);
student.addContent(age);
root.addContent(student);
Format format = Format.getCompactFormat();
format.setEncoding("gb2312"); //设置xml文件的字符为gb2312
format.setIndent(" "); //设置xml文件的缩进为4个空格
XMLOutputter XMLOut = new XMLOutputter(format);//在元素后换行,每一层元素缩排四格
XMLOut.output(doc, new FileOutputStream("studentinfo.xml"));
}
public static void main(String[] args) throws Exception
{
WriteXML w = new WriteXML();
System.out.println("Now we build an XML document .....");
w.BuildXML();
System.out.println("finished!");
}
}
生成的xml文档为:
<?xml version="1.0" encoding="gb2312"?>
<student-info>
<student>
<number>001</number>
<name>lnman</name>
<age>24</age>
</student>
</student-info>
读取xml文档的例子:
/*
* Created on 2004-10-9
*
*用jdom读取xml文档的例子
*
*/
/**
* @author lnman
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import org.jdom.output.*;
import org.jdom.input.*;
import org.jdom.*;
import java.io.*;
import java.util.*;
public class ReadXML
{
public static void main(String[] args) throws Exception
{
SAXBuilder builder = new SAXBuilder();
Document read_doc = builder.build("studentinfo.xml");
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");
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("------------------------------");
System.out.println();
}
}
}
Xpath例子:
JDOM的关于XPATH的api在org.jdom.xpath这个包里。这个包下,有一个抽象类XPath.java和实现类JaxenXPath.java, 使用时先用XPath类的静态方法newInstance(String xpath)得到XPath对象,然后调用它的selectNodes(Object context)方法或selectSingleNode(Object context)方法,前者根据xpath语句返回一组节点(List对象);后者根据一个xpath语句返回符合条件的第一个节点(Object类型)。请看jdom-1.0自带的范例程序:
它分析在web.xml文件中的注册的servlet的个数及参数个数,并输出角色名。
web.xml文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
-->
<web-app>
<servlet>
<servlet-name>snoop</servlet-name>
<servlet-class>SnoopServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>file </servlet-name>
<servlet-class>ViewFile</servlet-class>
<init-param>
<param-name>initial</param-name>
<param-value>1000</param-value>
<description>The initial value for the counter <!-- optional --></description>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mv</servlet-name>
<url-pattern>*.wm</url-pattern>
</servlet-mapping>
<distributed/>
<security-role>
<role-name>manager</role-name>
<role-name>director</role-name>
<role-name>president</role-name>
</security-role>
</web-app>
处理程序:
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import org.jdom.xpath.*;
/**
* <p><code>XPathReader</code> demonstrates how to
* read a Servlet 2.2 Web Archive file using XPath.
* </p>
*
* @author Jason Hunter
* @version 1.0
*/
public class XPathReader {
public static void main(String[] args) throws IOException, JDOMException {
if (args.length != 1) {
System.err.println("Usage: java XPathReader web.xml");
return;
}
String filename = args[0];//从命令行输入web.xml
PrintStream out = System.out;
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));//得到Document对象
// Print servlet information
XPath servletPath = XPath.newInstance("//servlet");//,选择任意路径下servlet元素
List servlets = servletPath.selectNodes(doc);//返回所有的servlet元素。
out.println("This WAR has "+ servlets.size() +" registered servlets:");
Iterator i = servlets.iterator();
while (i.hasNext()) {//输出servlet信息
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());
}
}
}
}
输出结果:
C:"java>java XPathReader web.xml
This WAR has 2 registered servlets:
snoop for SnoopServlet (it has 0 init params)
file for ViewFile (it has 1 init params)
This WAR contains 3 roles:
manager
director
president