Java XMl解析DOM4j实例

1、DOM4j读写xml实例  所需jar文件dom4j-1.6.1.jar

2、读xml文件名 test.xml

<?xml version="1.0" encoding="UTF-8"?>
<university name="pku">
    <college name="c1">
        <class name="class1">
            <student name="stu1" sex='male' age="21" />
            <student name="stu2" sex='female' age="20" />
            <student name="stu3" sex='female' age="20" />
        </class>
        <class name="class2">
            <student name="stu4" sex='male' age="19" />
            <student name="stu5" sex='female' age="20" />
            <student name="stu6" sex='female' age="21" />
        </class>
    </college>
    <college name="c2">
        <class name="class3">
            <student name="stu7" sex='male' age="20" />
        </class>
    </college>
    <college name="c3">
    </college>
</university>

3、读xml

public static void readXml() throws DocumentException{

SAXReader  reader = new SAXReader();
InputStream in= ParserXML.class.getResourceAsStream("test.xml");
Document doc=reader.read(in);
Element  root=doc.getRootElement();
readNode(root);
}

public static void readNode(Element root){
 if(root==null){return ;}
 //读取属性
  List<Attribute> attributesList=root.attributes();
  for(Attribute attr:attributesList){
  System.out.println(attr.getValue());
  }
  //读取元素
 List<Element> elementList=root.elements();
 for(Element elem:elementList){
readNode(elem);
}
}


4、生成xml

public static void write() throws IOException{
Document doc=DocumentHelper.createDocument();
Element book=doc.addElement("book");
book.addAttribute("name", "书籍");
Element english=book.addElement("english");
english.addAttribute("name", "英语");
english.setText("aabbccdd");
Element math=book.addElement("math");
math.addAttribute("name", "数学");
math.setText("11223344");
File file =new File("src/com/demo/test/book.xml");
if(file.exists()){
file.delete();
}
file.createNewFile();
XMLWriter out =new XMLWriter(new FileWriter(file));
out.write(doc);
out.flush();
out.close();
}


5、生成的xml文件 book.xml

<?xml version="1.0" encoding="UTF-8"?>
<book name="书籍"><english name="英语">aabbccdd</english><math name="数学">11223344</math></book>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值