1.新建文件名为:Jdomdemo.java,代码:
package com.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import com.inter.XmlDocument;
public class JDomDemo implements XmlDocument
{
public void createXml(String fileName)
{
Document document;
Element root;
root=new Element("employees");
document=new Document(root);
Element employee=new Element("employee");
root.addContent(employee);
Element name=new Element("name");
name.setText("ddvip");
employee.addContent(name);
Element sex=new Element("sex");
sex.setText("m");
employee.addContent(sex);
Element age=new Element("age");
age.setText("23");
employee.addContent(age);
XMLOutputter XMLOut = new XMLOutputter();
try {
XMLOut.output(document, new FileOutputStream(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void parserXml(String fileName)
{
SAXBuilder sax = new SAXBuilder();
try {
Document xmlDom = sax.build(new File(fileName));
Element root = xmlDom.getRootElement();
System.out.println(root.getName());
List childList = root.getChildren();
Iterator listIt = childList.iterator();
while(listIt.hasNext()){
Element element = (Element)listIt.next();
System.out.println(element.getName());
}
Element firstChild = (Element) childList.get(0);
List attrList = firstChild.getAttributes();
Iterator attrIt = attrList.iterator();
while(attrIt.hasNext()){
Attribute attr = (Attribute ) attrIt.next();
System.out.println(attr.getName());
System.out.println(attr.getValue());
System.out.println(attr.getAttributeType());
}
List sonList = firstChild.getChildren();
Iterator sonIt = sonList.iterator();
while(sonIt.hasNext()){
Element temp = (Element)sonIt.next();
System.out.println(temp.getName()+":"+temp.getValue());
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("----jdom 解析完毕-----");
}
}
2.编写测试类,TestJdom.java,代码如下:
public class TestDom
{
public static void main(String[] args)
{
Jdomdemo jdom= new Jdomdemo();
//创建的xml见图一
jdom.createXml("D://employee.xml");
//解析的xml见图二
jdom.parseXml("E://employee.xml");
}
}