📄 jdom 简介.txt
字号:
<?xml version="1.0" encoding="gb2312"?>
<student-info>
<student>
<number>001</number>
<name>lnman</name>
<age>24</age>
</student>
</student-info>
创建XML文档2:
public class CreateXML {
public void Create() {
try {
Document doc = new Document();
ProcessingInstruction pi=new ProcessingInstruction("xml-stylesheet","type="text/xsl" href="test.xsl"");
doc.addContent(pi);
Namespace ns = Namespace.getNamespace("http://www.bromon.org" );
Namespace ns2 = Namespace.getNamespace("other", "http://www.w3c.org" );
Element root = new Element("根元素", ns);
root.addNamespaceDeclaration(ns2);
doc.setRootElement(root);
Element el1 = new Element("元素一");
el1.setAttribute("属性", "属性一");
Text text1=new Text("元素值");
Element em = new Element("元素二").addContent("第二个元素");
el1.addContent(text1);
el1.addContent(em);
Element el2 = new Element("元素三").addContent("第三个元素");
root.addContent(el1);
root.addContent(el2);
//缩进四个空格,自动换行,gb2312编码
XMLOutputter outputter = new XMLOutputter(" ", true,"GB2312");
outputter.output(doc, new FileWriter("test.xml"));
}catch(Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
new CreateXML().Create();
}
}
2、读取xml文档的例子:
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();
}
}
}
3、DTD验证的:
public class XMLWithDTD {
public void validate() {
try {
SAXBuilder builder = new SAXBuilder(true);
builder.setFeature("http://xml.org/sax/features/validation";,true);
Document doc = builder.build(new FileReader("author.xml"));
System.out.println("搞掂");
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc, System.out);
}catch(Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
new XMLWithDTD().validate();
}
}
需要说明的是,这个程序没有指明使用哪个DTD文件。DTD文件的位置是在XML中指定的,而且DTD不支持命名空间,一个XML只能引用一个DTD,所以程序直接读取XML中指定的DTD,程序本身不用指定。不过这样一来,好象就只能使用外部式的DTD引用方式了?高人指点。
4、XML Schema验证的:
public class XMLWithSchema {
String xml="test.xml";
String schema="test-schema.xml";
public void validate() {
try {
SAXBuilder builder = new SAXBuilder(true);
//指定约束方式为XML schema
builder.setFeature("http://apache.org/xml/features/validation/schema";, true);
//导入schema文件
builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";,schema);
Document doc = builder.build(new FileReader(xml));
System.out.println("搞掂");
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc, System.out);
}catch(Exception e) {
System.out.println("验证失败:"+e);
}
}
}
上面的程序就指出了要引入的XML Schema文件的位置。
系统默认输出是UTF-8,这有可能导致出现乱码。
5、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.*;
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
6、数据输入要用到XML文档要通过org.jdom.input包,反过来需要org.jdom.output。如前面所说,关是看API文档就能够使用。
我们的例子读入XML文件exampleA.xml,加入一条处理指令,修改第一本书的价格和作者,并添加一条属性,然后写入文件exampleB.xml:
//exampleA.xml
<?xml version="1.0" encoding="GBK"?>
<bookList>
<book>
<name>Java编程入门</name>
<author>张三</author>
<publishDate>2002-6-6</publishDate>
<price>35.0</price>
</book>
<book>
<name>XML在Java中的应用</name>
<author>李四</author>
<publishDate>2002-9-16</publishDate>
<price>92.0</price>
</book>
</bookList>
//testJDOM.java
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*;
public class TestJDOM{
public static void main(String args[])throws Exception{
SAXBuilder sb = new SAXBuilder();
//从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了
Document doc = sb.build(new FileInputStream("exampleA.xml"));
ProcessingInstruction pi = new ProcessingInstruction//加入一条处理指令
("xml-stylesheet","href=\"bookList.html.xsl\" type=\"text/xsl\"");
doc.addContent(pi);
Element root = doc.getRootElement(); //得到根元素
java.util.List books = root.getChildren(); //得到根元素所有子元素的集合
Element book = (Element)books.get(0); //得到第一个book元素
//为第一本书添加一条属性
Attribute a = new Attribute("hot","true");
book.setAttribute(a);
Element author = book.getChild("author"); //得到指定的字元素
author.setText("王五"); //将作者改为王五
//或 Text t = new Text("王五");book.addContent(t);
Element price = book.getChild("price"); //得到指定的字元素
//修改价格,比较郁闷的是我们必须自己转换数据类型,而这正是JAXB的优势
author.setText(Float.toString(50.0f));
String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK");
outp.output(doc, new FileOutputStream("exampleB.xml"));
}
};
执行结果exampleB.xml:
<?xml version="1.0" encoding="GBK"?>
<bookList>
<book hot=”true”>
<name>Java编程入门</name>
<author>50.0</author>
<publishDate>2002-6-6</publishDate>
<price>35.0</price>
</book>
<book>
<name>XML在Java中的应用</name>
<author>李四</author>
<publishDate>2002-9-16</publishDate>
<price>92.0</price>
</book>
</bookList>
<?xml-stylesheet href="bookList.html.xsl" type="text/xsl"?>
在默认情况下,JDOM的Element类的getText()这类的方法不会过滤空白字符,如果你需要过滤,用setTextTrim() 。
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -