对xml的操作-java版

来源:互联网 发布:JAVA http post 多附件 编辑:程序博客网 时间:2024/05/22 14:02

1.摘要

在对微信公众号的开发中,由于微信推送消息都是xml的格式,这里简单介绍一下对xml的操作。

2.操作类型

2.1.xml数据转为集合的方法
这里需要引用dom4j-1.6.1.jar

/**     * ********************************************************           * 项目名称:       * 方法说明:xml转为map集合     * 参数: @param request     * 参数: @return     * 参数: @throws Exception        * 返回值: Map<String,String>        * 创建人:苏叶      * 创建时间:2016年5月27日 上午9:14:24        * 修改备注:        *********************************************************     */  public static Map<String ,String > xmlToMap(HttpServletRequest request) throws Exception{      Map<String ,String > map=new HashMap<String, String>();      SAXReader reader=new SAXReader();      InputStream ins=request.getInputStream();      Document doc=reader.read(ins);      Element root=doc.getRootElement();      List<Element> list=root.elements();      for(Element e:list){          map.put(e.getName(), e.getText());      }      ins.close();      return map;  }

2.2.将对象类型转换为xml类型
这里用到xstream-1.4.8.jar

/**   * ********************************************************         * 项目名称:     * 方法说明:将文本消息对象转为xml   * 参数: @param textMessage   * 参数: @return      * 返回值: String      * 创建人:苏叶    * 创建时间:2016年5月27日 上午9:30:47      * 修改备注:      *********************************************************   */  public static String textMessageToXml(TextMessage textMessage){      XStream xstream=new XStream();      xstream.alias("xml", textMessage.getClass());      return xstream.toXML(textMessage);  }

jar下载地址:
dom4j-1.6.1.jar
http://download.csdn.net/detail/qiyeliuli/9532820
xstream-1.4.8.jar
http://download.csdn.net/detail/qiyeliuli/9532823

0 0
原创粉丝点击