jdom的使用

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
(1)使用JDOM首先要指定使用什么解析器。如:
SAXBuilder builder=new SAXBuilder(false); 这表示使用的是默认的解析器
(2)得到Document,我们以后要进行的所有操作都是对这个Document操作的:
Document doc=builder.build(xmlpath);
(3)得到根元素:
Element books=doc.getRootElement();
在JDOM中所有的节点(DOM中的概念)都是一个org.jdom.Element类,当然他的子节点也是一个org.jdom.Element类。
(4)得到元素(节点)的集合:
List booklist=books.getChildren("book");
这表示得到“books”元素的所在名称为“book”的元素,并把这些元素都放到一个List集合中
(5)轮循List集合
for (Iterator iter = booklist.iterator(); iter.hasNext();) {
Element book = (Element) iter.next();

还有一种轮循方法是:
for(int i=0;I<booklist.size();I++){
Element book=(Element)booklist.get(i);
}
(6)取得元素的属性:
String email=book.getAttributeValue("email");
取得元素book的属性名为“email”的属性值。
(7)取得元素的子元素(为最低层元素)的值:
String name=book.getChildTextTrim("name");
注意的是,必须确定book元素的名为“name”的子元素只有一个。
(8)改变元素(为最低层元素)的值:
book.getChild("name").setText("alterrjzjh");
这只是对Document的修改,并没有在实际的XML文档中进行修改
(9)保存Document的修改到XML文件中:
XMLOutputter outputter=new XMLOutputter();
outputter.output(doc,new FileOutputStream(xmlpath));

我们先要有一个XMLOutputter类,再把已经修改了的Document保存进XML文档中。
到此。用JDOM解析和处理XML文档讲解完了,麻雀虽小,五脏俱全。现在已对JDOM有个整体上的概念了吧
JDOM包概述(转)
2009-10-01 21:02

二、JDOM 包概览
JDOM是由以下几个包组成的
org.JDOM
org.JDOM.input
org.JDOM.output
org.JDOM.adapters
org.JDOM.transform 
三、JDOM 类说明

org.JDOM
这个包里的类是你解析xml文件后所要用到的所有数据类型。
Attribute
CDATA
Coment
DocType
Document
Element
EntityRef
Namespace
ProscessingInstruction
Text

org.JDOM.transform
在涉及xslt格式转换时应使用下面的2个类
JDOMSource
JDOMResult

org.JDOM.input
输入类,一般用于文档的创建工作
SAXBuilder
DOMBuilder
ResultSetBuilder

org.JDOM.output
输出类,用于文档转换输出
XMLOutputter
SAXOutputter
DomOutputter
JTreeOutputter

使用前注意事项:
1.JDOM对于JAXP 以及 TRax 的支持
JDOM 支持JAXP1.1:你可以在程序中使用任何的parser工具类,默认情况下是JAXP的parser。
制定特别的parser可用如下形式
SAXBuilder parser 
= new SAXBuilder("org.apache.crimson.parser.XMLReaderImpl");
Document doc = parser.build("http://www.cafeconleche.org/");
// work with the document...
JDOM也支持TRaX:XSLT可通过JDOMSource以及JDOMResult类来转换(参见以后章节)
2.注意在JDOM里文档(Document)类由org.JDOM.Document 来表示。这要与org.w3c.dom中的Document区别开,这2种格式如何转换在后面会说明。
以下如无特指均指JDOM里的Document。


四、JDOM主要使用方法
1.Ducument类
(1)Document的操作方法:
Element root = new Element("GREETING");
Document doc = new Document(root);
root.setText("Hello JDOM!");
或者简单的使用Document doc = new Document(new Element("GREETING").setText("Hello JDOM!t"));

这点和DOM不同。Dom则需要更为复杂的代码,如下:
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root =doc.createElement("root");
Text text = doc.createText("This is the root");
root.appendChild(text);
doc.appendChild(root);


注意事项:JDOM不允许同一个节点同时被2个或多个文档相关联,要在第2个文档中使用原来老文档中的节点的话。首先需要使用detach()把这个节点分开来。

(2)从文件、流、系统ID、URL得到Document对象:
DOMBuilder builder = new DOMBuilder();
Document doc = builder.build(new File("jdom_test.xml"));

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(url);
在新版本中DOMBuilder 已经Deprecated掉 DOMBuilder.builder(url),用SAX效率会比较快。

这里举一个小例子,为了简单起见,使用String对象直接作为xml数据源:

public jdomTest() {
String textXml = null;
textXml = "<note>";
textXml = textXml +
"<to>aaa</to><from>bbb</from><heading>ccc</heading><body>ddd</body>";
textXml = textXml + "</note>";
SAXBuilder builder = new SAXBuilder();
Document doc = null;
Reader in= new StringReader(textXml);
try {
doc = builder.build(in);
Element root = doc.getRootElement();
List ls = root.getChildren();//注意此处取出的是root节点下面的一层的Element集合
for (Iterator iter = ls.iterator(); iter.hasNext(); ) {
Element el = (Element) iter.next();
if(el.getName().equals("to")){
System.out.println(el.getText());
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (JDOMException ex) {
ex.printStackTrace();
}
}

很简单把。


(3)DOM的document和JDOM的Document之间的相互转换使用方法,简单!
DOMBuilder builder = new DOMBuilder();
org.jdom.Document jdomDocument = builder.build(domDocument);
// work with the JDOM document…

DOMOutputter converter = new DOMOutputter();
org.w3c.dom.Document domDocument = converter.output(jdomDocument);
// work with the DOM document…

2.XML文档输出
XMLOutPutter类:
JDOM的输出非常灵活,支持很多种io格式以及风格的输出
Document doc = new Document(...);
XMLOutputter outp = new XMLOutputter();
// Raw output
outp.output(doc, fileOutputStream);
// Compressed output
outp.setTextTrim(true);
outp.output(doc, socket.getOutputStream());
// Pretty output
outp.setIndent(" ");
outp.setNewlines(true);
outp.output(doc, System.out);
......
详细请参阅最新的JDOM API手册


3.Element 类:
(1)浏览Element树
//获得根元素element
Element root = doc.getRootElement();
// 获得所有子元素的一个list
List allChildren = root.getChildren();
// 获得指定名称子元素的list
List namedChildren = root.getChildren("name");
//获得指定名称的第一个子元素
Element child = root.getChild("name");
(这里的List是java.util.List)

JDOM给了我们很多很灵活的使用方法来管理子元素
List allChildren = root.getChildren();
// 删除第四个子元素
allChildren.remove(3);
// 删除叫“jack”的子元素
allChildren.removeAll(root.getChildren("jack"));

root.removeChildren("jack"); // 便捷写法
// 加入
allChildren.add(new Element("jane"));

root.addContent(new Element("jane")); // 便捷写法
allChildren.add(0, new Element("first"));


(2)移动Elements:
在JDOM里很简单
Element movable = new Element("movable");
parent1.addContent(movable); // place
parent1.removeContent(movable); // remove
parent2.addContent(movable); // add

在Dom里
Element movable = doc1.createElement("movable");
parent1.appendChild(movable); // place
parent1.removeChild(movable); // remove
parent2.appendChild(movable); // 出错!

补充:
纠错性
JDOM的Element构造函数(以及它的其他函数)会检查element是否合法。
而它的add/remove方法会检查树结构,检查内容如下:
1.在任何树中是否有回环节点
2.是否只有一个根节点
3.是否有一致的命名空间(Namespaces)

(3)Element的text内容读取
<description>
A cool demo
</description>

// The text is directly available
// Returns "/n A cool demo/n"
String desc = element.getText();

// There's a convenient shortcut
// Returns "A cool demo"
String desc = element.getTextTrim();

(4)Elment内容修改
element.setText("A new description");
3.可正确解释特殊字符
element.setText("<xml> content");
4.CDATA的数据写入、读出
element.addContent(new CDATA("<xml> content"));
String noDifference = element.getText();

混合内容
element可能包含很多种内容,比如说

<table>
<!-- Some comment -->
Some text
<tr>Some child element</tr>
</table>

取table的子元素tr
String text = table.getTextTrim();
Element tr = table.getChild("tr");

也可使用另外一个比较简单的方法
List mixedCo = table.getContent();
Iterator itr = mixedCo.iterator();
while (itr.hasNext()) {
Object o = i.next();
if (o instanceof Comment) {
...
}
// 这里可以写成Comment, Element, Text, CDATA,ProcessingInstruction, 或者是EntityRef的类型
}
// 现在移除Comment,注意这里游标应为1。这是由于回车键也被解析成Text类的缘故,所以Comment项应为1。
mixedCo.remove(1);

4.Attribute类
<table width="100%" border="0"> </table>
//获得attribute
String width = table.getAttributeValue("width");
int border = table.getAttribute("width").getIntValue();
//设置attribute
table.setAttribute("vspace", "0");
// 删除一个或全部attribute
table.removeAttribute("vspace");
table.getAttributes().clear();

5.处理指令(Processing Instructions)操作
一个Pls的例子
<?br?>
<?cocoon-process type="xslt"?>
| |
| |
目标 数据

处理目标名称(Target)
String target = pi.getTarget();
获得所有数据(data),在目标(target)以后的所有数据都会被返回。
String data = pi.getData();
获得指定属性的数据
String type = pi.getValue("type");
获得所有属性的名称
List ls = pi.getNames();

6.命名空间操作
<xhtml:html 
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:title>Home Page</xhtml:title>
</xhtml:html>

Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");
List kids = html.getChildren("title", xhtml);
Element kid = html.getChild("title", xhtml);
kid.addContent(new Element("table", xhtml));

7.XSLT格式转换
使用以下函数可对XSLT转换
最后如果你需要使用w3c的Document则需要转换一下。
public static Document transform(String stylesheet,Document in)
throws JDOMException {
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(new StreamSource(stylesheet));
JDOMResult out = new JDOMResult();
transformer.transform(new JDOMSource(in), out);
return out.getDeocument();
}
catch (TransformerException e) {
throw new JDOMException("XSLT Trandformation failed", e);
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章