packagevedio.webservice;importjava.io.IOException;importjava.util.Iterator;importjava.util.List;importorg.dom4j.Document;importorg.dom4j.DocumentException;importorg.dom4j.DocumentHelper;importorg.dom4j.Element;importorg.dom4j.io.XMLWriter;public classXmlUtil {public static voidmain(String[] args) {
System.out.println(createXml());
readXml(createXml());
}public staticString createXml(){//根元素
Element root = DocumentHelper.createElement("student");//创建文档
Document document =DocumentHelper.createDocument(root);//添加属性
root.addAttribute("name","zs");
Element child1= root.addElement("hello");
Element child2= root.addElement("word");
child1.setText("hello Text");
child2.setText("word Text");//输出//输出到控制台
XMLWriter xmlWriter = newXMLWriter();try{
xmlWriter.write(document);
}catch(IOException e) {
e.printStackTrace();
}
System.out.println();
System.out.println("------------------");// //输出到文件// //格式//OutputFormat format = new OutputFormat(" ", true);//设置缩进为4个空格,并且另起一行为true//XMLWriter xmlWriter2 = new XMLWriter(//new FileOutputStream("student.xml"), format);//xmlWriter2.write(document2);//
// //另一种输出方式,记得要调用flush()方法,否则输出的文件中显示空白//XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("student2.xml"),//format);//xmlWriter3.write(document2);//xmlWriter3.flush();//<?xml version="1.0" encoding="UTF-8"?>//hello Textword Text
returndocument.asXML();
}public static voidreadXml(String sxml){try{//解析xml文件//SAXReader saxReader = new SAXReader();//
//Document document = saxReader.read(new File("students.xml"));//解析xml字符串
Document document =DocumentHelper.parseText(sxml);
Element root=document.getRootElement();
System.out.println(root.getName());
List children =root.elements();
System.out.println(children.size());//获取特定名称的子元素
List childList2 = root.elements("hello");
System.out.println("hello child size: " +childList2.size());//获取名字为指定名称的第一个子元素
Element firstWorldElement = root.element("world");//输出其属性//System.out.println("first World Attr: "//+ firstWorldElement.attribute(0).getName() + "="//+ firstWorldElement.attributeValue("name"));//迭代输出
for (Iterator iter =root.elementIterator(); iter.hasNext();)
{
Element e=(Element) iter.next();//System.out.println(e.attributeValue("name"));
System.out.println(e.getText());
}
}catch(DocumentException e) {
e.printStackTrace();
}
}
}