解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。

/** 转换成XML格式字符串 **/
public static String doXMLStr(Map<String, String> map) {
StringBuffer xml_sbuff = new StringBuffer("<xml>");
for (String key : map.keySet()) {
xml_sbuff.append("<" + key + ">").append("<![CDATA[" + map.get(key) + "]]>").append("</" + key + ">");
}

xml_sbuff.append("</xml>");

return xml_sbuff.toString();
}

/**
* 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
*/
@SuppressWarnings("unchecked")
public static Map<String, String> doXMLParse(String strxml) throws JDOMException, IOException {
// strxml = strxml.replace("<![CDATA[", "").replace("]]>", "");

if (null == strxml || "".equals(strxml)) {
return null;
}
Map<String, String> m = new HashMap<String, String>();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();

List<Element> list = root.getChildren();
Iterator<Element> it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List<Element> children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = XMLUtil.getChildrenText(children);
}

m.put(k, v);
}
// 关闭流
in.close();
return m;
}

/**
* 获取子结点的xml
*/
@SuppressWarnings("unchecked")
public static String getChildrenText(List<Element> children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator<Element> it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List<Element> list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}

public static void main(String[] args) {

String strxml = "<xml><ToUserName><![CDATA[gh_0cbb7ebf88c5]]></ToUserName><FromUserName><![CDATA[oo5CB0SRe4zJX9Flr3S7cIEy8ac8]]></FromUserName><CreateTime>1535779238</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[VIEW]]></Event><EventKey><![CDATA[https://open.weixin.qq.com/connect/oauth2/authorize?appid=e10adc3949ba59abbe56e057f20f883e&redirect_uri=http://system.xbr518.cn/LittleWhiteService/weChatUserInfo/getUserMessage.do&response_type=code&scope=snsapi_userinfo&state=10001#wechat_redirect]]></EventKey><MenuId>424151876</MenuId></xml>";

try {
Map<String, String> a = doXMLParse(strxml);
System.out.println(a);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

上一篇:++ -- 自增,自减 一元运算符


下一篇:(深度剖析数据在内存中的存储) C语言从入门到入土(进阶篇)