Dom4j 操作 XML

只需导入dom4j.jar即可
Dom4j解析XML


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Dom4jReardXML {

	
	 public static void main(String args[]) {
	        testParseXMLData("D:/MyWorkspace/mytest/person.xml");
	  } 
	 
	   /**
	     * @param xmlFilePath xml文件路径
	     * @return Document对象
	     */
	    public static Document parse2Document(String xmlFilePath){
	        SAXReader reader = new SAXReader();
	        Document document = null;
	        File f = null;
	        try {
	        	f = new File(xmlFilePath);
	            InputStream in = new FileInputStream(f);
	            document = reader.read(in);
	        } catch (Exception e) {
	            System.out.println(e.getMessage());
	            System.out.println("读取文件发生异常,请检查CLASSPATH和文件名是否存在!");
	            e.printStackTrace();
	        }
	        return document;
	    }

	    public static void testParseXMLData(String xmlFileName) {
	         
	        Document document = null;
			document = parse2Document(xmlFileName);
			 
	        //获取文档的根元素
	        Element root = document.getRootElement();
	        
	        StringBuffer sb = new StringBuffer();
	        sb.append("通过Dom4j解析XML,并输出数据:\n");
	        sb.append(xmlFileName + "\n");
	        
	        sb.append("----------------遍历start----------------\n");
	        //遍历当前元素(根元素)的子元素
	        for (Iterator i_pe = root.elementIterator(); i_pe.hasNext();) {
	            Element e_pe = (Element) i_pe.next();
	            
	            //获取当前元素的名字
	            String person = e_pe.getName();
	            //获取当前元素的属性
	            String id = e_pe.attributeValue("id");
	            String sex = e_pe.attributeValue("sex");
	            String name = e_pe.element("name").getText();
	            String age = e_pe.element("age").getText();
	            
	            //将数据存放到缓冲区字符串对象中
	            sb.append(person + ":\n");
	            sb.append("\tid=" + id + " sex=" + sex + "\n");
	            sb.append("\t" + "name=" + name + " age=" + age + "\n");

	            //获取当前元素e_pe下的子元素adds
	            Element e_adds = e_pe.element("adds");
	            sb.append("\t" + e_adds.getName() + "\n");

	            //遍历当前元素e_adds(在此是adds元素)的子元素
	            for (Iterator i_adds = e_adds.elementIterator(); i_adds.hasNext();) {
	                Element e_add = (Element) i_adds.next();
	                String code = e_add.attributeValue("code");
	                String add = e_add.getTextTrim();
	                sb.append("\t\t" + e_add.getName() + ":" + " code=" + code + " value=\"" + add + "\"\n");
	            }
	            sb.append("\n");
	        }
	        sb.append("-----------------遍历end-----------------\n");
	        System.out.println(sb.toString());

	        //选择性节点,遍历
	        System.out.println("---------通过XPath获取一个元素----------");
	        Node node1 = document.selectSingleNode("/doc/person");
	        System.out.println("输出节点:" +
	                "\t"+node1.asXML());

	        Node node2 = document.selectSingleNode("/doc/person/@sex");
	        System.out.println("输出节点:" +
	                "\t"+node2.asXML());

	        Node node3 = document.selectSingleNode("/doc/person[name=\"zhangsan\"]/age");
	        System.out.println("输出节点:" +
	                "\t"+node3.asXML());

	        System.out.println("\n---------XPath获取List节点测试------------");
	        List list = document.selectNodes("/doc/person[name=\"zhangsan\"]/adds/add");
	        for(Iterator it=list.iterator();it.hasNext();){
	            Node nodex=(Node)it.next();
	            System.out.println(nodex.asXML());
	        }

	        System.out.println("\n---------通过ID获取元素的测试----------");
	        System.out.println("陷阱:通过ID获取,元素ID属性名必须为“大写ID”,小写的“id”会认为是普通属性!");
	        String id22 = document.elementByID("22").asXML();
	        String id23 = document.elementByID("23").asXML();
	        
	        String id24 = null;
	        if (document.elementByID("24") != null) {
	            id24 = document.elementByID("24").asXML();
	        } else {
	            id24 = "null";
	        }

	        System.out.println("id22=  " + id22);
	        System.out.println("id23=  " + id23);
	        System.out.println("id24=  " + id24);
	    }

}



Dom4j生成XML


import java.io.File;
import java.io.FileOutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class CreateXML {
	
	 public static void main(String[] args) {
		 CreateXML c = new CreateXML();
		 Document document = c.createDocument();
		 c.writeXML(document, "d:/message.xml");
	  }
	
	 /**
	  * 写入文件
	  */
	 
	 private void writeXML(Document doc, String path){
		 
		 try {
			 XMLWriter writer = new XMLWriter(new FileOutputStream(new File(path)));
			 writer.write(doc);
			 writer.close();
			 
			 OutputFormat format = OutputFormat.createPrettyPrint();
			 format.setEncoding("GBK");
			 //输出到控制台
			 writer = new XMLWriter(System.out, format);
			 writer.write(doc);
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
	 }
	 
	  /** 
	    * 建立Document XML文件 
	  **/ 
	  private Document createDocument() {  
	         Document document = DocumentHelper.createDocument();  
	         Element rootElement = document.addElement(QName.get("Message", "http://www.baidu.com"));  
	         Element catalogElement = rootElement.addElement("Header");  
	         catalogElement.addElement("Version").addText("1.0");  
	         catalogElement.addElement("MessageId").addText("STO");  
	         catalogElement.addElement("CorrelationId").addText("10000");  
	         catalogElement.addElement("FromSite").addText("AIRPORT_SITE");  
	         catalogElement.addElement("ToService").addText("RegisterService");  
	         catalogElement.addElement("Personnel").addText("0001223");  
	         catalogElement.addElement("Reserve").addText("STRING");  
	         catalogElement.addElement("GroupId").addText("1000001");  
	         catalogElement.addElement("GroupSize").addText("3");  
	         catalogElement.addElement("GroupIndex").addAttribute("name", "abc")
	         		.addElement("GroupIndex2").addText("2");
	         Element articleElement = catalogElement.addElement("ToSites");  
	         articleElement.addElement("ToSite").addText("DATA_CENTER_SITE");  
	         return document;  
	     }  

	  
	 
	
	
}

你可能感兴趣的:(Java综合)