Dom4j解析xml使用方法

 

package dao;

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;

import java.io.*;
import java.util.List;
public class Dom4j {    //读取已有的xml
	static public void xml(){
		try{
		SAXReader sax=new SAXReader() ;
		Document doc=sax.read(new File("c://xhf.xml") ) ;
                Element element=doc.getRootElement() ;
                List<Element> list=element.elements()         ;
               for(Element el:list){
        	 System.out.println(el.getName()) ;
        	 System.out.println(el.attributeValue("value"));
        	 List<Element> fax=el.elements()     ;
        	  for(Element fvv:fax){
        		 System.out.println(fvv.getText());
        		 System.out.println(fvv.getName()) ;
        	  }
        }
        System.out.println(element.getName()) ;
		
		}catch(Exception e){
			e.printStackTrace() ;
		}
	}
	static public void main(String[] args){ //创建一个新的xml
		try{
		Document document=DocumentHelper.createDocument();
		Element element=document.addElement("fangzi") ;
		element.addAttribute("mianji","120") ;
		Element e1=element.addElement("chuang") ;
		e1.addAttribute("shaungren","shaung") ;
		e1.addText("我想有个家");
		OutputFormat format = OutputFormat.createPrettyPrint();
		/** 指定XML编码*/
		format.setEncoding("GBK");
		XMLWriter xmlw=new XMLWriter(new FileWriter(new File("c://jia.xml")),format) ;
		 xmlw.write(document) ;
		 xmlw.close() ;
		}catch(Exception e){
			e.printStackTrace() ;
		}
	}

}

你可能感兴趣的:(DAO,C++,c,xml,C#)