dom4j读取XML简单使用

 

 

  测试例子1 

@SuppressWarnings("unchecked")
public class TestDom4j {
        private static SAXReader reader;
         
        static{
                 reader = new SAXReader();
        }

        /**
         * 得到文档的document
         * @param is
         * @return
         * @throws DocumentException
         */
        public static Document getDocument( InputStream is ) throws DocumentException{
                return  reader.read(is );
        }
        /**
         * 得到 xml文件的根元素
         * @param doc
         * @return
         */
        
        public static Element getRoot( Document doc){
                return doc.getRootElement();
        }
        
        
        
        /**
         * document 的遍历 ,通过递归的方式         
         * @param is
         * @return
         * @throws DocumentException
         */
        public static List readXML( Element root ) throws DocumentException{
                List list = new ArrayList();
                list = getData(root);
                return list;
        }

        /**
         * 递归元素数据
         * @param root
         * @return
         */
        private static List getData(Element root) {
                 
//                System.out.println( "节点总数:::"+root.nodeCount());
                for(int i=0;i<root.nodeCount();i++){
                         Node node = root.node(i);
                         if(node instanceof Element ){
                                 getData((Element)node);
//                                 System.out.println("element node !");
                         }else{
                              System.out.println( node.getPath()+" == "+node.getText()+" "); 
                         }
                }
                return null;
        }
        

         /** 查找功能
          *  /books/book/@show  xpath        遍历这个路径下的说有show属性
          *  /books/book             表示xpath     此路径下的所有元素
          * @param node
          * @param xpath
          */
        public static List getByXpath(Node node,String xpath){
                
                List list = node.selectNodes(xpath);
                for(int i=0;i<list.size();i++){
//                        Attribute attr = (Attribute) list.get(i);
//                        System.out.println( attr.getValue());
//                        System.out.println( list.get(i));
                }
                return list;
        }
        
        public static Element addEle(Element parentNode, String childNodeName){
                return parentNode.addElement(childNodeName);
        }
        
        /**
         * 向文件中写入 东西 测试
         * @param filepath
         * @throws DocumentException
         * @throws IOException
         */
        public static void writeFile(String filepath  ) throws DocumentException, IOException          {         
                File f = new File(filepath);
                Document doc = reader.read(f);
                Element root = doc.getRootElement();
                root.addElement("book").addAttribute("name", "我得书").addElement("title").addText("感觉不是很爽!!");
                 
                OutputFormat format = OutputFormat.createPrettyPrint(); 
                XMLWriter writer = new XMLWriter(new FileWriter(new File(filepath)),format);
                writer.write(doc);
                writer.close();          
        }
        
        
        /**
         * 增删改的应用
         * @throws DocumentException 
         * @throws IOException 
         */
        public static void rem_add_update() throws DocumentException, IOException{
                File f = new File("D://book.xml");
                Document doc = reader.read(f);
                Element root = doc.getRootElement();
                
//                List list = getByXpath(root, "/books/book/@show");
//                for(int i=0;i<list.size();i++){
//                        Attribute attr = (Attribute) list.get(i);
//                        String val = attr.getValue();
//                         if("none".equals( val )){
//                                 attr.setValue("处理");
//                         }
//                }
 
                List list_ele = getByXpath(root, "/books/book");
                System.out.println( list_ele.size());
                for(int i=0;i<list_ele.size();i++){
                        Element ele = (Element) list_ele.get(i);
                        ele.addAttribute("public", "5");                                                               //添加属性    如果属性存在则修改属性
                        //删除文档中左后一个元素
                        if( i==(list_ele.size()-1) ) root.remove( ele   );         
                }
                
                
                XMLWriter writer = new XMLWriter(new FileWriter(new File("D://book.xml")) );
                writer.write(doc);
                writer.close();                
        }
 
        public static void main(String[] args) throws DocumentException, IOException {
  
//           InputStream is = TestDom4j.class.getClassLoader().getSystemResourceAsStream ("book.xml");
//            Document doc = getDocument(is);
//            Element root = getRoot(doc);
//            readXML( root );


                File f = new File("D://book.xml");
                Document doc = reader.read(f);
                Element root = doc.getRootElement();
                
//                List list = getByXpath(root, "/books/book/@show");
//                for(int i=0;i<list.size();i++){
//                        Attribute attr = (Attribute) list.get(i);
//                        String val = attr.getValue();
//                         if("none".equals( val )){
//                                 attr.setValue("处理");
//                         }
//                }
   
//                getByXpath(root, "/books/book");
        }
}

 

------------ ---xml文件

<?xml version="1.0" encoding="UTF-8"?>
<books>
        <book show="yes">
                <title>此处的添加方法 是根元素books已经存在的情况下dom4j 练习21</title>
        </book>
        <book show="no">
                <title>java 变成思想</title>
        </book>
        <book show="yes">
                <title>java程序设计</title>
        </book>        
        <book show="none">
                <title>java程序设计</title>
        </book>                
        
</books>

 

   

 

 

测试的例子2

 

package dom4j;

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

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

public class Dom4jDemo {
	/**
	 * 
	 * @param fileName
	 *            生成的xml文件名
	 * @param txtName
	 *            包含的对账文件txt文件名
	 */
	public void createXml(String fileName, String txtName) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("root");
		
		Element head = root.addElement("head");
		Element type = head.addAttribute("type", "0");
		Element code = head.addAttribute("code", "3003");
		
		Element yhlb = head.addElement("yhlb");
		yhlb.setText("01");
		Element username = head.addElement("username");
		username.setText("gsyh");
		Element password = head.addElement("password");
		password.setText("zheshimima");
		
		Element body = root.addElement("body");
		Element data = body.addElement("data");
		Element dzwjm = data.addElement("dzwjm");
		dzwjm.setText(txtName);
		try {
			// 写入文件
			Writer fileWriter = new FileWriter(fileName);
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
			xmlWriter.write(document);
			xmlWriter.close();
		 
			
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

	}

	/**
	 * 
	 * @param fileName
	 *            要解析的文件名
	 * @return 解析xml文件得到的需要对账的文件名
	 */
	public String parserXml(String fileName) {
		String findFileName = "";
		File inputXml = new File(fileName);
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(inputXml);
			Element root = document.getRootElement();
			for (Iterator i = root.elementIterator(); i.hasNext();) {
				Element head = (Element) i.next();
				for (Iterator j = head.elementIterator(); j.hasNext();) {
					Element elem = (Element) j.next();
					System.out.println(elem.getName() + ":" + elem.getText());
					for (Iterator k = elem.elementIterator(); k.hasNext();) {
						Element last = (Element) k.next();
						System.out.println(last.getName() + ":"
								+ last.getText());
						findFileName = last.getText();
					}

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

	/**
	 * 测试main方法
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Dom4jDemo demo = new Dom4jDemo();
//		demo.createXml("D://request.xml", "test.txt");
		demo.parserXml("d://request.xml");
	}
}

 

 

 

 

你可能感兴趣的:(dom4j)