java 生成xml

// 1、生成XML
@Test
public void createApplicationConfigXML(){
//建立document对象
try {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");//添加文档根
root.addComment("这个一个注释");//加入一行注释
Element request = root.addElement("request"); //添加root的子节点
request.addAttribute("type", "cat");
request.addAttribute("flow", "tong");
request.addAttribute("time", "2009");
Element pro = request.addElement("pro");
pro.addAttribute("type", "att");
pro.addAttribute("name", "附件");
pro.addText("测试哈子");

Element cd = request.addElement("pro");
cd.addAttribute("type", "cd");
cd.addAttribute("name", "特殊字符过滤");
cd.addCDATA("特殊字符");

//输出全部原始数据,在编译器中显示
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");//根据需要设置编码
XMLWriter writer = new XMLWriter(System.out, format);
document.normalize();
writer.write(document);
writer.close();
// 输出全部原始数据,并用它生成新的我们需要的XML文件
XMLWriter writer2 = new XMLWriter(new FileWriter(new File("d://test.xml")), format);
writer2.write(document); //输出到文件
writer2.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

 

//解析xml

 

@Test
public void parseApplicationConfigXML(){
try {
SAXReader sax = new SAXReader();
Document xmlDoc = sax.read(new File("d://test.xml"));
Element root = xmlDoc.getRootElement();//根节点
Iterator it = root.elementIterator("request");
while(it.hasNext()){
Element request = (Element)it.next();
System.out.println(request.getName());
System.out.println(request.attributeValue("type"));
System.out.println(request.attributeValue("flow"));
System.out.println(request.attributeValue("time"));

}
System.out.println("-------------------------------------------");
List list = root.selectNodes("//pro");
for(int i = 0; i < list.size(); i++){
Element pro = (Element)list.get(i);
System.out.println(pro.getName());
System.out.println(pro.attributeValue("type"));
System.out.println(pro.attributeValue("name"));
System.out.println(pro.getText());
System.out.println("+++++++++++++++++++++++++++++++++");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。