(3)DOM的document和JDOM的Document之间的相互转换使用方法,简单!
DOMBuilder builder = new DOMBuilder();
org.jdom.Document jdomDocument = builder.build(domDocument);
DOMOutputter converter = new DOMOutputter();// work with the JDOM document…
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();
outp.output(doc, fileOutputStream); // Raw output
outp.setTextTrim(true); // Compressed output
outp.output(doc, socket.getOutputStream());
outp.setIndent(" ");// Pretty output
outp.setNewlines(true);
outp.output(doc, System.out);
3.Element 类:
(1)浏览Element树
Element root = doc.getRootElement();//获得根元素element
List allChildren = root.getChildren();// 获得所有子元素的一个list
List namedChildren = root.getChildren("name");// 获得指定名称子元素的list
Element child = root.getChild("name");//获得指定名称的第一个子元素
JDOM给了我们很多很灵活的使用方法来管理子元素(这里的List是java.util.List)
List allChildren = root.getChildren();
allChildren.remove(3); // 删除第四个子元素
allChildren.removeAll(root.getChildren("jack"));// 删除叫“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
(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 text
- <tr>Some child elementtr>
- 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);