public class XmlUtil { /*
* 利用dom4j解析xml文件内容,并返回map数据形式
* path是.xml文件所在的路径
*/
public static Map<String,String> paserXmlByDOM4J(String path) throws Exception{ path=ServletActionContext.getServletContext().getRealPath(path); SAXReader reader = new SAXReader(); Document doc = reader.read(new FileInputStream(new File(path))); Map<String,String> xml=paserXml(doc); return xml; } //传入xml格式的string,转化为xml类型,然后解析其内容,返回map数据形式
/*
* strXml是xml格式的字符串
*/ public static Map<String,String> strToXmlAndPaserXml(String strXml) throws Exception{ SAXReader reader = new SAXReader(); Document doc = reader.read(new ByteArrayInputStream(strXml.getBytes("UTF-8"))); Map<String,String> xml=paserXml(doc); return xml; } //遍历解析xml数据 public static Map<String,String> paserXml(Document doc) throws Exception{ Map<String,String> xml=new HashMap<String,String>(); Element root = doc.getRootElement(); Iterator it = root.elementIterator(); Element element; while (it.hasNext()) { element = (Element) it.next(); xml.put(element.getName(),element.getText()); } return xml; } }