(一)利用JDOM生成xml文件
package com.huawei;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class Demo1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
test1();
}
public static void test1(){
Document document=new Document();
Element rootElement=new Element("root");
document.addContent(rootElement);
Comment comment=new Comment("this is comment");
rootElement.addContent(comment);
Element e=new Element("hello");
e.setAttribute("baidu","www.baidu.com");
rootElement.addContent(e);
Element e2=new Element("World");
Attribute attribute=new Attribute("wangyi", "www.163.com");
e2.setAttribute(attribute);
rootElement.addContent(e2);
Element e3=new Element("wuhan");
e3.setAttribute("huawei", "www.huawei.com").setAttribute("souhu", "www.souhu.com");//方法链的编程风格
rootElement.addContent(e3);
//Format format=Format.getRawFormat();//默认的格式
Format format=Format.getPrettyFormat();
format.setIndent(" ");
XMLOutputter out=new XMLOutputter(format);
try {
out.output(document, new FileOutputStream("jdom2.xml"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
(二)解析普通的xml文件
下面是xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--This is comment-->
<百度 名字="www.baidu.com">
<!--This is comment too-->
</百度>
<搜狐 名字="www.souhu.com" />
</root>
解析上面的zz.xml文件的代码如下:
public static void test1(){
SAXBuilder saxBuilder=new SAXBuilder();
try {
Document document=saxBuilder.build("zz.xml");
Element root=document.getRootElement();
System.out.println(root.getName());
Element baiduElement=root.getChild("百度");
/*System.out.println(baiduElement.getName()+"...."+baiduElement.getValue());*/
List<Attribute> list=baiduElement.getAttributes();
int size=list.size();
for(int i=0;i<size;i++){
Attribute attribute=list.get(i);
String name=attribute.getName();
String value=attribute.getValue();
System.out.println(name+"..."+value);
}
} catch (Exception e) {
// TODO: handle exception
}
}
输出如下:
root
名字...www.baidu.com