dom4j parsing example

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.XMLWriter;

/**
 * @Title: TestDom4j.java
 * @Package
 * @Description: Parse the xml string
 * @author is everywhere
 * @date 2012-11-20 5:14:05 pm
 * @version V1.0
 */
public class TestDom4j {

 public static void readStringXml(String xml) {
  Document doc = null;
  try {

   // Read and parse the XML document
   // SAXReader is a pipe that reads the xml file in a stream
   //
   // SAXReader reader = new SAXReader(); //User.hbm.xml represents the xml document you want to parse
   // Document document = reader.read(new File("User.hbm.xml"));
   // The following is by parsing the xml string
   doc = DocumentHelper.parseText(xml); // Convert string to XML

   Element rootElt = doc.getRootElement(); // get the root node
   System.out.println("Root node: " + rootElt.getName()); // Get the name of the root node

   Iterator iter = rootElt.elementIterator("head"); // Get the child node head under the root node

   // Traverse the head node
   while (iter.hasNext()) {

    Element recordEle = (Element) iter.next();
    String title = recordEle.elementTextTrim("title"); // Get the title value of the child node under the head node
    System.out.println("title:" + title);

    Iterator iters = recordEle.elementIterator("script"); // Get the child node script under the child node head

    // Traverse the Response node under the Header node
    while (iters.hasNext()) {

     Element itemEle = (Element) iters.next();

     String username = itemEle.elementTextTrim("username"); // Get the value of the byte point username under the child node script under the head
     String password = itemEle.elementTextTrim("password");

     System.out.println("username:" + username);
     System.out.println("password:" + password);
    }
   }
   Iterator iterss = rootElt.elementIterator("body"); // /Get the child node body under the root node
   // Traverse the body node
   while (iterss.hasNext()) {

    Element recordEless = (Element) iterss.next();
    String result = recordEless.elementTextTrim("result"); // Get the result value of the child node under the body node
    System.out.println("result:" + result);

    Iterator itersElIterator = recordEless.elementIterator("form"); // Get the child node form under the child node body
    // Traverse the Response node under the Header node
    while (itersElIterator.hasNext()) {

     Element itemEle = (Element) itersElIterator.next();

     String banlce = itemEle.elementTextTrim("banlce"); // Get the value of the byte point banlce under the child node form under the body
     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 convert xml string to map
  * @param xml
  * @return Map
  */
 public static Map readStringXmlOut(String xml) {
  Map map = new HashMap();
  Document doc = null;
  try {
   // convert string to XML
   doc = DocumentHelper.parseText(xml);
   // get the root node
   Element rootElt = doc.getRootElement();
   // get the name of the root node
   System.out.println("Root node: " + rootElt.getName());

   // Get the child node head under the root node
   Iterator iter = rootElt.elementIterator("head");
   // Traverse the head node
   while (iter.hasNext()) {

    Element recordEle = (Element) iter.next();
    // Get the title value of the child node under the head node
    String title = recordEle.elementTextTrim("title");
    System.out.println("title:" + title);
    map.put("title", title);
    // Get the child node script under the child node head
    Iterator iters = recordEle.elementIterator("script");
    // Traverse the Response node under the Header node
    while (iters.hasNext()) {
     Element itemEle = (Element) iters.next();
     // Get the value of the byte point username under the child node script under the head
     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);
    }
   }

   // Get the child node body under the root node
   Iterator iterss = rootElt.elementIterator("body");
   // Traverse the body node
   while (iterss.hasNext()) {
    Element recordEless = (Element) iterss.next();
    // Get the result value of the child node under the body node
    String result = recordEless.elementTextTrim("result");
    System.out.println("result:" + result);
    // Get the child node form under the child node body
    Iterator itersElIterator = recordEless.elementIterator("form");
    // Traverse the Response node under the Header node
    while (itersElIterator.hasNext()) {
     Element itemEle = (Element) itersElIterator.next();
     // Get the value of the byte point banlce under the child node form under the body
     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) {

  // The following is an example of the xml string that needs to be parsed
  /*
   * String xmlString = "<html>" + "<head>" + "<title>dom4j parsing an example</title>"
   * + "<script>" + "<username>yangrong</username>" +
   * "<password>123456</password>" + "</script>" + "</head>" + "<body>" +
   * "<result>0</result>" + "<form>" + "<banlce>1000</banlce>" +
   * "<subID>36242519880716</subID>" + "</form>" + "</body>" + "</html>";
   */

  /*
   * Map folder = readStringXmlOut (xmlString); Iterator iters =
   * map.keySet().iterator(); while (iters.hasNext()) { String key =
   * iters.next().toString(); // 拿到键 String val = map.get(key).toString();
   * // get the value System.out.println(key + "=" + val); }
   */

  // readStringXml (xmlString);

  String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><message><result><classifies><classify id=\"PS_ConstructDesignAudit\" name=\"主网项目:施工图审批\" count=\"13\"><record index=\"1\"><title></title><assigner></assigner><assignDate></assignDate><url>http://10.10.5.5:7009/web/ssoLogin.do?modelUrl=%2Flcam%2Fproject%2Fprojectplan%2Fconstructdesign%2FConstructDesignTab.jsp%3FtagFlag%3DtodoTag%26pDesktop%3Dyes%26nodeString%3Dnull%3Anull%3BPS_ConstructDesignAudit%3B000137%26pMenu%3Dyes%26projectType%3D1%26moduleId%3DCSG_ConstructDesign</url></record><record index=\"2\"><title></title><assigner></assigner><assignDate></assignDate><url>http://10.10.5.5:7009/web/ssoLogin.do?modelUrl=%2Flcam%2Fproject%2Fprojectplan%2Fconstructdesign%2FConstructDesignTab.jsp%3FtagFlag%3DtodoTag%26pDesktop%3Dyes%26nodeString%3Dnull%3Anull%3BPS_ConstructDesignAudit%3B000137%26pMenu%3Dyes%26projectType%3D1%26moduleId%3DCSG_ConstructDesign</url></record></classify></classifies><totalCount>61</totalCount></result></message>";
  try {
   Document document = DocumentHelper.parseText(xmlString);
   // output operation
   // OutputFormat format = OutputFormat.createPrettyPrint() ; //Instantiate
   // format.setEncoding("GBK") ;
   // XMLWriter writer = new XMLWriter(new FileOutputStream(new
   // File("d:" + File.separator + "dom4j_demo.xml")),format) ;
   // writer.write(docment) ; // do the output
   // writer.close() ;

   List listNodes = document
     .selectNodes("message/result/classifies/classify");
   for (int i = 0; i < listNodes.size(); i++) {
    // get classify
    Element element = (Element) listNodes.get(i);
    // get record
    for (Iterator it = element.elementIterator("record"); it
      .hasNext();) {
     Element temp = (Element) it.next();
     System.out.println(temp.element("url").getText());
     break;
    }
   }
  } catch (Exception e) {
   e.printStackTrace ();
  }

 }

}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326940655&siteId=291194637