用Dom4j解析Xml



package com.util;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
* 此类主要用来创建和解析Xml
* @author wenlong
*
*/
public class XmlUtil {

/*
  *默认构造
  */
public XmlUtil(){}


private final String XMLURL = "E:\\text.xml";





/*
  * 用DOM4J来读取Xml
  */
public void readXml(String url)
{
  SAXReader reader = new SAXReader();
  try
  {
   Document root = reader.read(new File(url));
  
  
   //用XPath指定路径
   List list = root.selectNodes("/home/parent/firstChildamie/name");
   Iterator iter = list.iterator();
   while(iter.hasNext())
   {
    Element att = (Element)iter.next();
    System.out.println(att.getTextTrim());
   }
  }catch(Exception ex)
  {
   System.out.println("reader:"+ex.getMessage());
   ex.printStackTrace();
  }
 
}



/**
  * 用DOM4J来创建一定格式的Xml
  *
  */
public void writerXml(String url)
{
  Document doc = DocumentHelper.createDocument();
 
 
  Element root = doc.addElement("home");
  root.addAttribute("homecode", "0001");
 
  root.addComment("family");
 
  Element fumu = root.addElement("parent");
 
  Element firstChild = fumu.addElement("firstChild");
  Element firstChildamie = fumu.addElement("firstChildamie");
  Element secondChild = fumu.addElement("secondChild");
 
 
  Element name = firstChild.addElement("name");
  name.setText("张文龙");
  Element age = firstChild.addElement("age");
  age.setText("21");
 
  name = firstChildamie.addElement("name");
  name.setText("李瑜");
  age = firstChildamie.addElement("age");
  age.setText("21");
 
 
  name = secondChild.addElement("name");
  name.setText("张文洋");
  age = secondChild.addElement("age");
  age.setText("2");
  try
  {
  
   //解决中文问题
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("gb2312");
   XMLWriter output = new XMLWriter(new FileWriter(url),format);
   output.write(doc);
   output.close();
  }catch(Exception ex)
  {
   System.out.println("writerXmlerror:"+ex.getMessage());
   ex.printStackTrace();
  }
 
 
}



public static void main(String[] args)
{
  XmlUtil xml = new XmlUtil();
  xml.writerXml("E:\\text.xml");
  xml.readXml("E:\\text.xml");
}
}

你可能感兴趣的:(xml)