1.构造解析器
方法1:
import org.jdom.input. * ;
SAXBuilder saxBuilder = new SAXBuilder();
File file = new File( " src/c03/students.xml " );
Document doc = saxBuilder.build(file);
方法2:
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File( " src/c03/students.xml " );
org.w3c.dom.Document doc = db.parse(file);
DOMBuilder domBuilder = new DOMBuilder ();
org.jdom.Document doc = domBuilder.build(doc);
2.jdom函数
(1)创建xml文档
Document doc = new Document();
Element eltRoot = new Element("student");
doc.setRootElement(eltRoot);
(2)添加元素和属性
Element eltStu = new Element("student");
Element eltName = new Element("name");
Element eltAge = new Element("age");
eltName.setText("王五");
eltAge.setText("19");
eltStu.addContent(eltName);
eltStu.addContent(eltAge);
eltStu.setAttribute("sn", "03");
(3)访问元素
- 访问根元素: Element root = doc.getRootElement();
- 得到某元素下所有子元素:LIst children = element.getChildren();
- 得到指定元素下所有子元素:LIst children = element.getChildren("student");
- 得到指定元素的第一个子元素:Element child = element.getChild("student");
- 返回指定子节点的内容文本值: getChildText("childname")
- 返回该元素的内容文本值:getText()
- 取得元素的子元素(为最低层元素)的值:String name=book.getChildTextTrim("name");
(4)访问属性
- 得到指定元素下所有属性:List attrList = element.getAttributes();
- 得到指定属性:Attribute attr = element.getAttribute("sn");
- 得到指定属性的值:String attrValue = element.getAttributeValue("sn");
(5)删除元素和属性
- 删除指定元素下所有子元素:element.removeChildren("student");
- 删除指定元素下第一个子元素:element.removeChild("student");
- 删除指定属性:element.removeAttribute("sn");
(6)输出文档
XMLOutputter xmlOut = new XMLOutputter();
Format fmt = Format.getPrettyFormat();
fmt.setEncoding("GB2312");
fmt.setIndent(" ");
xmlOut.setFormat(fmt);
xmlOut.output(doc, new FileOutputStream("src/c03/students.xml"));
或者输出到xmlOut.output(doc, System.out);
3.JDOM实例
import org.jdom. * ;
import org.jdom.input. * ;
import org.jdom.output. * ;
public class JDOMConvert {
/**
* @param args
*/
public static void main(String[] args) {
SAXBuilder saxBuilder = new SAXBuilder();
File file = new File( " src/c03/students.xml " );
try {
Document doc = saxBuilder.build(file);
// add element
Element eltStu = new Element( " student " );
Element eltName = new Element( " name " );
Element eltAge = new Element( " age " );
eltName.setText( " 王五 " );
eltAge.setText( " 19 " );
eltStu.addContent(eltName);
eltStu.addContent(eltAge);
eltStu.setAttribute( " sn " , " 03 " );
Element root = doc.getRootElement();
root.addContent(eltStu);
// remove element
root.removeChild( " student " );
// modify element
root.getChild( " student " ).getChild( " age " ).setText( " 23 " );
// output to screen
XMLOutputter xmlOut = new XMLOutputter();
Format fmt = Format.getPrettyFormat();
fmt.setEncoding( " GB2312 " );
fmt.setIndent( " " );
xmlOut.setFormat(fmt);
xmlOut.output(doc, new FileOutputStream( " src/c03/students.xml " ));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
catch (JDOMException e) {
System.out.println(e.getMessage());
}
}
}