大家好,XML解析不依赖任何Jar包的编写模式,关键词:Pattern、Matcher使用。
工具类如下
/** * Xml工具类 * @author 章力 * @微信 zl4828 */ public class XmlUtil { /** * 从消息message中提取出指定的tagName节点,包括他得子节点. * * @param xmlMessage * @param tagName * @return * @throws Exception */ public static String pareXml(String xmlMessage, String tagName) { String regex = ".*?(<"+tagName+">.*?</"+tagName+">)|(<"+tagName+"/>)"; Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); Matcher matcher = pattern.matcher(xmlMessage); if (matcher.find()) { xmlMessage = matcher.group(1); return xmlMessage; } else { throw new RuntimeException("无法提取xml消息体.tagName = " + tagName); } } /** * 从消息message中提取出指定的tagName节点中间的内容 * * @param xmlMessage * @param tagName * @return * @throws Exception */ public static String pareXmlContent(String xmlMessage, String tagName) { String regex = "\\<" + tagName + ">(.*?)\\</" + tagName + ">"; Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); Matcher matcher = pattern.matcher(xmlMessage); if (matcher.find()) { xmlMessage = matcher.group(1); return xmlMessage; } else { throw new RuntimeException("无法提取xml消息体.tagName = " + tagName); } } /** * 返回匹配到的所有节点 * * @param xmlMessage * @param tagName * @return * @throws Exception */ public static Matcher pareXmlMatcher(String xmlMessage, String tagName) { String regex = ".*?(<"+tagName+">.*?</"+tagName+">)|(<"+tagName+"/>)"; Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); Matcher matcher = pattern.matcher(xmlMessage); return matcher; } }
使用实例
/** * 解析返回的XML,沫沫金提供支持微信@zl4828 */ Matcher matcher = XmlUtil.pareXmlMatcher(resultXml, "Result"); while (matcher.find()) { System.out.println(XmlUtil.pareXmlContent(matcher.group(),"hosName")); }
示例XML内容
<?xml version="1.0" encoding="UTF-8"?> <Response><MessageHeader> <code>0</code> <desc>成功</desc> </MessageHeader><List> <Result> <hosOrgCode>43523202X61010311A1001</hosOrgCode> <hosName>西安市第九医院</hosName> <hospitalAdd>沫沫金</hospitalAdd> <hospitalRule></hospitalRule> <hospitalWeb></hospitalWeb> <trafficGuide></trafficGuide> <hospitalDesc>专注网页设计、Web前端工程</hospitalDesc> <hospitalTel>微信:zl4828</hospitalTel> <hospitalGrade></hospitalGrade> <payMode>|3|</payMode> <orderMode>|2|</orderMode> <isSpTime>1</isSpTime> </Result> <Result> <hosOrgCode>43720037161011311A5211</hosOrgCode> <hosName>西安市第八医院</hosName> <hospitalAdd></hospitalAdd> <hospitalRule></hospitalRule> <hospitalWeb></hospitalWeb> <trafficGuide></trafficGuide> <hospitalDesc>网络营销</hospitalDesc> <hospitalTel>15319419526</hospitalTel> <hospitalGrade>1</hospitalGrade> <payMode>|3|</payMode> <orderMode>|2|</orderMode> <isSpTime>1</isSpTime> </Result> </List></Response>
总结:不想千篇一律,以上是你尝鲜的动力。
作者:沫沫金@zl4828微信号