dom4j解析xml(之一)

package com.lyc.xhdx.util;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
 
public class ReadXml {
 
 static Logger log = Logger.getLogger(ReadXml.class);
   
 public static Map<String, String> parseXMLFileD(String fileName) {
  Map<String, String> map = new HashMap<String, String>();
  try {
   SAXReader reader = new SAXReader();
   // 创建一个新的字符串
   StringReader in = new StringReader(fileName);
   // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
   InputSource source = new InputSource(in);
   //获得Document
   Document document = reader.read(source);
   //获得根节点元素
   Element root = document.getRootElement();
   //获得根节点的子节点元素结合
   List nodes = root.elements("item");
   //循环集合
   for (Iterator it = nodes.iterator(); it.hasNext();) {
    //获得元素的下一个节点
    Element nextNode = (Element) it.next();
    //获得name属性值
    String name = nextNode.attribute("name").getValue();
    //获得value属性值
    String value = nextNode.attribute("value").getValue();
    //以key(name)-value(value)存入map
    map.put(name, value);
   }
  } catch (Exception e) {
   
   log.error("解析XML出错"+e);
   
  }
  return map;
 }
 public static void main(String[] args) {
  String fileName = "<"
    + "?"
    + "xml version"
    + "="
    + "'"
    + "1.0"
    + "'"
    + " encoding='GB2312' ?>"
    + "<crp>"
    + "<item name='agentid' value='[email protected]' />"
    + "<item name='agent_orderid' value='215688' />"
    +
    "<item name='order_money' value='50' />"
    +
    "<item name='tranid' value='515000' />"
    + "<item name='status' value='2' />"
    + "<item name='result_no' value='0000' />"
    + "<item name='verify_string' value='874e66194142bb9e23af38e3d6dac780fd456' />"
    + "</crp>";
  Map<String, String> map = ReadXml.parseXMLFileD(fileName);
  System.err.println(map.get("agentid"));
  System.err.println(map.get("agent_orderid"));
  System.err.println(map.get("order_money"));
  System.err.println(map.get("tranid"));
  System.err.println(map.get("status"));
  System.err.println(map.get("result_no"));
  System.err.println(map.get("verify_string"));
 }
}

你可能感兴趣的:(java,apache,xml,log4j)