dom4j

生成xml,或转化为string
package dom4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import java.io.*;

public class XmlDom4J {
	public void generateDocument(){
		Document document = DocumentHelper.createDocument();
		     Element catalogElement = document.addElement("catalog");
		     catalogElement.addComment("An XML Catalog");
		     catalogElement.addProcessingInstruction("target","text");
		     Element journalElement =  catalogElement.addElement("journal");
		     journalElement.addAttribute("title", "XML Zone");
		     journalElement.addAttribute("publisher", "IBM developerWorks");
		     Element articleElement=journalElement.addElement("article");
		     articleElement.addAttribute("level", "Intermediate");
		     articleElement.addAttribute("date", "December-2001");
		     Element  titleElement=articleElement.addElement("title");
		     titleElement.setText("Java configuration with XML Schema");
		     Element authorElement=articleElement.addElement("author");
		     Element  firstNameElement=authorElement.addElement("firstname");
		     firstNameElement.setText("Marcello");
		     Element lastNameElement=authorElement.addElement("lastname");
		     lastNameElement.setText("Vitaletti");
//		     document.addDocType("catalog",
//		                           null,"file://c:/Dtds/catalog.dtd");
		     String str = document.asXML();
//             doc = DocumentHelper.parseText(xml); // 将字符串转为XML
		     System.out.println(str);
		     
		    try{
		    XMLWriter output = new XMLWriter(
		            new FileWriter( new File("c:/catalog/catalog.xml") ));
		        output.write( document );
		        output.close();
		        }
		     catch(IOException e){System.out.println(e.getMessage());}
		}
		public static void main(String[] argv){
			XmlDom4J dom4j=new XmlDom4J();
			dom4j.generateDocument();
		}
}


修改xml

package dom4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Attribute;
import java.util.List;
import java.util.Iterator;
import org.dom4j.io.XMLWriter;
import java.io.*;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader; 

public class Dom4JParser {
	public void modifyDocument(File inputXml){
		  try{
		   SAXReader saxReader = new SAXReader();
		   Document document = saxReader.read(inputXml);
		   List list = document.selectNodes("//article/@level" );
		   Iterator iter=list.iterator();
		   while(iter.hasNext()){
		    Attribute attribute=(Attribute)iter.next();
		    if(attribute.getValue().equals("Intermediate"))
		      attribute.setValue("Introductory"); 
		       }
		   
		   list = document.selectNodes("//article/@date" );
		   iter=list.iterator();
		   while(iter.hasNext()){
		    Attribute attribute=(Attribute)iter.next();
		    if(attribute.getValue().equals("December-2001"))
		      attribute.setValue("October-2002");
		       }
		   list = document.selectNodes("//article" );
		   iter=list.iterator();
		   while(iter.hasNext()){
		    Element element=(Element)iter.next();
		    Iterator iterator=element.elementIterator("title");
		      while(iterator.hasNext()){
		        Element titleElement=(Element)iterator.next();
		        if(titleElement.getText().equals("Java configuration with XMLchema"))
		        titleElement.setText("Create flexible and extensible XML schema");
		                                          }
		                                }
		    list = document.selectNodes("//article/author" );
		    iter=list.iterator();
		     while(iter.hasNext()){
		     Element element=(Element)iter.next();
		     Iterator iterator=element.elementIterator("firstname");
		     while(iterator.hasNext()){
		      Element firstNameElement=(Element)iterator.next();
		      if(firstNameElement.getText().equals("Marcello"))
		      firstNameElement.setText("Ayesha");
		                                     }
		                              }
		    list = document.selectNodes("//article/author" );
		    iter=list.iterator();
		     while(iter.hasNext()){
		      Element element=(Element)iter.next();
		      Iterator iterator=element.elementIterator("lastname");
		     while(iterator.hasNext()){
		      Element lastNameElement=(Element)iterator.next();
		      if(lastNameElement.getText().equals("Vitaletti"))
		      lastNameElement.setText("Malik");
		                                  }
		                               }
		     XMLWriter output = new XMLWriter(
		      new FileWriter( new File("c:/catalog/catalog-modified.xml") ));
		     output.write( document );
		     output.close();
		   }
		 
		  catch(DocumentException e)
		                 {
		                  System.out.println(e.getMessage());
		                            }
		  catch(IOException e){
		                       System.out.println(e.getMessage());
		                    }
		 }
		 public static void main(String[] argv){
		  Dom4JParser dom4jParser=new Dom4JParser();
		  dom4jParser.modifyDocument(new File("c:/catalog/catalog.xml"));
		 }
}


读取xml格式的字符串

//先加入dom4j.jar包 
package dom4j;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 
 import org.dom4j.Document;
 import org.dom4j.DocumentException;
 import org.dom4j.DocumentHelper;
 import org.dom4j.Element;
 
 public class TestDom4j {
 
     public void readStringXml(String xml) {
         Document doc = null;
         try {
 
             // 读取并解析XML文档
             // SAXReader就是一个管道,用一个流的方式,把xml文件读出来
             // 
             // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档
             // Document document = reader.read(new File("User.hbm.xml"));
             // 下面的是通过解析xml字符串的
             doc = DocumentHelper.parseText(xml); // 将字符串转为XML
 
             Element rootElt = doc.getRootElement(); // 获取根节点
             System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
 
             Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head
 
             // 遍历head节点
             while (iter.hasNext()) {
 
                 Element recordEle = (Element) iter.next();
                 String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值
                 System.out.println("title:" + title);
 
                 Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script
 
                 // 遍历Header节点下的Response节点
                 while (iters.hasNext()) {
 
                     Element itemEle = (Element) iters.next();
 
                     String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值
                     String password = itemEle.elementTextTrim("password");
 
                     System.out.println("username:" + username);
                     System.out.println("password:" + password);
                 }
             }
             Iterator iterss = rootElt.elementIterator("body"); ///获取根节点下的子节点body
             // 遍历body节点
             while (iterss.hasNext()) {
 
                 Element recordEless = (Element) iterss.next();
                 String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值
                 System.out.println("result:" + result);
 
                 Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form
                 // 遍历Header节点下的Response节点
                 while (itersElIterator.hasNext()) {
 
                     Element itemEle = (Element) itersElIterator.next();
 
                     String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值
                     String subID = itemEle.elementTextTrim("subID");
 
                     System.out.println("banlce:" + banlce);
                     System.out.println("subID:" + subID);
                 }
             }
         } catch (DocumentException e) {
             e.printStackTrace();
 
         } catch (Exception e) {
             e.printStackTrace();
 
         }
     }
 
     /**
      * @description 将xml字符串转换成map
      * @param xml
      * @return Map
      */
     public static Map readStringXmlOut(String xml) {
         Map map = new HashMap();
         Document doc = null;
         try {
             // 将字符串转为XML
             doc = DocumentHelper.parseText(xml); 
             // 获取根节点
             Element rootElt = doc.getRootElement(); 
             // 拿到根节点的名称
             System.out.println("根节点:" + rootElt.getName()); 
 
             // 获取根节点下的子节点head
             Iterator iter = rootElt.elementIterator("head"); 
             // 遍历head节点
             while (iter.hasNext()) {
 
                 Element recordEle = (Element) iter.next();
                 // 拿到head节点下的子节点title值
                 String title = recordEle.elementTextTrim("title"); 
                 System.out.println("title:" + title);
                 map.put("title", title);
                 // 获取子节点head下的子节点script
                 Iterator iters = recordEle.elementIterator("script"); 
                 // 遍历Header节点下的Response节点
                 while (iters.hasNext()) {
                     Element itemEle = (Element) iters.next();
                     // 拿到head下的子节点script下的字节点username的值
                     String username = itemEle.elementTextTrim("username"); 
                     String password = itemEle.elementTextTrim("password");
 
                     System.out.println("username:" + username);
                     System.out.println("password:" + password);
                     map.put("username", username);
                     map.put("password", password);
                 }
             }
 
             //获取根节点下的子节点body
             Iterator iterss = rootElt.elementIterator("body"); 
             // 遍历body节点
             while (iterss.hasNext()) {
                 Element recordEless = (Element) iterss.next();
                 // 拿到body节点下的子节点result值
                 String result = recordEless.elementTextTrim("result"); 
                 System.out.println("result:" + result);
                 // 获取子节点body下的子节点form
                 Iterator itersElIterator = recordEless.elementIterator("form"); 
                 // 遍历Header节点下的Response节点
                 while (itersElIterator.hasNext()) {
                     Element itemEle = (Element) itersElIterator.next();
                     // 拿到body下的子节点form下的字节点banlce的值
                     String banlce = itemEle.elementTextTrim("banlce"); 
                     String subID = itemEle.elementTextTrim("subID");
 
                     System.out.println("banlce:" + banlce);
                     System.out.println("subID:" + subID);
                     map.put("result", result);
                     map.put("banlce", banlce);
                     map.put("subID", subID);
                 }
             }
         } catch (DocumentException e) {
             e.printStackTrace();
         } catch (Exception e) {
             e.printStackTrace();
         }
         return map;
     }
 
     public static void main(String[] args) {
 
         // 下面是需要解析的xml字符串例子
         String xmlString = "<html>" + "<head>" + "<title>dom4j解析一个例子</title>"
                 + "<script>" + "<username>yangrong</username>"
                 + "<password>123456</password>" + "</script>" + "</head>"
                 + "<body>" + "<result>0</result>" + "<form>"
                 + "<banlce>1000</banlce>" + "<subID>36242519880716</subID>"
                 + "</form>" + "</body>" + "</html>";
 
         /*
          * Test2 test = new Test2(); test.readStringXml(xmlString);
          */
         Map map = readStringXmlOut(xmlString);
         Iterator iters = map.keySet().iterator();
         while (iters.hasNext()) {
             String key = iters.next().toString(); // 拿到键
             String val = map.get(key).toString(); // 拿到值
             System.out.println(key + "=" + val);
         }
     }
 
 }



 


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值