java xml生成与读取_XML生成与读取

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值