Dom4J小程序1.
package WildCat.Xml.Dom4j;
import java.io.FileOutputStream;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Dom4J1_1 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// //创建文档 第一种方式
// Document document=DocumentHelper.createDocument();
// //创建根元素节点
// Element root=DocumentHelper.createElement("企业名单");
// document.setRootElement(root);
//创建文档的第二种方式
Element root=DocumentHelper.createElement("企业名单");
Document document=DocumentHelper.createDocument(root);
root.addAttribute("地区", "华北");
Element name=root.addElement("名字");
Element address=root.addElement("地址");
Element tel=root.addElement("电话");
name.addText("WildCat科技有限公司");
address.addText("烟台");
tel.addText("18253576788");
//输出到命令行
XMLWriter writer=new XMLWriter();
writer.write(document);
//输入硬盘
OutputFormat format=new OutputFormat(" ",true);
XMLWriter writer2=new XMLWriter(new FileOutputStream("企业名单.xml"),format);
writer2.write(document);
}
}
小程序2:
package WildCat.Xml.Dom4j;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4JTest1_2 {
/**
* @param args
*
* 通过DOM4J读取XML
* @throws DocumentException
*/
public static void main(String[] args) throws DocumentException {
//
SAXReader reader=new SAXReader();
Document document=reader.read(new File("企业名单.xml"));
Element root=document.getRootElement();
System.out.println(root.getName());
//List ChildList=root.elements();
System.out.println(root.attributeValue("地区"));
for (Iterator iter=root.elementIterator();iter.hasNext();)
{
Element e=(Element)iter.next();
System.out.println(e.getName()+":"+e.getStringValue());
}
}
}