java操作xml----dom4j

package com.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jXml {

 public static void main(String[] args) {
  try {
   createXml("D:\\xmlFileByDom4j.xml");
   parserXml("D:\\xmlFileByDom4j.xml");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void createXml(String fileName) throws IOException {
  Document document = DocumentHelper.createDocument();
  Element list = document.addElement("UserList");
  for (int i = 0; i <3; i++) {
   Element user = list.addElement("user");
   user.addAttribute("ID", i+1+"");
   Element name = user.addElement("name");
   name.setText("WeiJun Hu");
   Element sex = user.addElement("sex");
   sex.setText("M");
   Element age = user.addElement("age");
   age.setText("21");
   Element email = user.addElement("email");
   email.setText("962884205@qq.com");
  }
  
  
  Writer fileWriter = new FileWriter(fileName);
  XMLWriter xmlWriter = new XMLWriter(fileWriter);
  xmlWriter.write(document);
  xmlWriter.close();
 }

 public static void parserXml(String fileName) throws MalformedURLException {
  File inputXml = new File(fileName);
  SAXReader saxReader = new SAXReader();
  try {
   Document document = saxReader.read(inputXml);
   
   Element list = document.getRootElement();
   
   for (Iterator i = list.elementIterator(); i.hasNext();) {
    Element user = (Element) i.next();
    Attribute attribute = user.attribute("ID");
    Integer id = Integer.parseInt(attribute.getValue());
    System.out.println("ID:"+id);
    for (Iterator j = user.elementIterator(); j.hasNext();) {
     Element node = (Element) j.next();
     System.out.println(node.getName() + ":" + node.getText());
    }

   }
  } catch (DocumentException e) {
   System.out.println(e.getMessage());
  }
  System.out.println("dom4j parserXml");
 }
}

 

dom4j.jar下载地址

 

https://dl.pandaidea.com/jarfiles/d/dom4j/dom4j-1.4.jar.zip


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值