沫沫金-XML节点解析(List内容)不依赖任何Jar包_JDK原生函数

前端之家收集整理的这篇文章主要介绍了沫沫金-XML节点解析(List内容)不依赖任何Jar包_JDK原生函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

大家好,XML解析不依赖任何Jar包的编写模式,关键词:Pattern、Matcher使用。


工具类如下

/**
*Xml工具类
*@author章力
*@微信zl4828
*/
publicclassXmlUtil{

	/**
*从消息message中提取出指定的tagName节点,包括他得子节点.
*
*@paramxmlMessage
*@paramtagName
*@return
*@throwsException
*/
	publicstaticStringpareXml(StringxmlMessage,StringtagName)
{
Stringregex=".*?(<"+tagName+">.*?</"+tagName+">)|(<"+tagName+"/>)";
Patternpattern=Pattern.compile(regex,Pattern.DOTALL);
Matchermatcher=pattern.matcher(xmlMessage);

if(matcher.find())
{
xmlMessage=matcher.group(1);
returnxmlMessage;
}
else
{
thrownewRuntimeException("无法提取xml消息体.tagName="+tagName);
}
}

	/**
*从消息message中提取出指定的tagName节点中间的内容
*
*@paramxmlMessage
*@paramtagName
*@return
*@throwsException
*/
	publicstaticStringpareXmlContent(StringxmlMessage,StringtagName)
{
Stringregex="\\<"+tagName+">(.*?)\\</"+tagName+">";
Patternpattern=Pattern.compile(regex,Pattern.DOTALL);
Matchermatcher=pattern.matcher(xmlMessage);
if(matcher.find())
{
xmlMessage=matcher.group(1);
returnxmlMessage;
}
else
{
thrownewRuntimeException("无法提取xml消息体.tagName="+tagName);
}
}
	
	/**
*返回匹配到的所有节点
*
*@paramxmlMessage
*@paramtagName
*@return
*@throwsException
*/
	publicstaticMatcherpareXmlMatcher(StringxmlMessage,StringtagName)
{
		Stringregex=".*?(<"+tagName+">.*?</"+tagName+">)|(<"+tagName+"/>)";
Patternpattern=Pattern.compile(regex,Pattern.DOTALL);
Matchermatcher=pattern.matcher(xmlMessage);
returnmatcher;
}
}

使用实例

/**
*解析返回的XML,沫沫金提供支持微信@zl4828
*/
Matchermatcher=XmlUtil.pareXmlMatcher(resultXml,"Result");
while(matcher.find()){
	System.out.println(XmlUtil.pareXmlContent(matcher.group(),"hosName"));
	}

示例XML内容

<?xmlversion="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微信号

原文链接:https://www.f2er.com/xml/295828.html

猜你在找的XML相关文章