拥有包含
结构的XML文件<codes>
<condition>
<code>395</code>
<description>Moderate or heavy snow in area with thunder</description>
<day_icon>wsymbol_0012_heavy_snow_showers</day_icon>
<night_icon>wsymbol_0028_heavy_snow_showers_night</night_icon>
</condition>
<condition>
<code>392</code>
<description>Patchy light snow in area with thunder</description>
<day_icon>wsymbol_0016_thundery_showers</day_icon>
<night_icon>wsymbol_0032_thundery_showers_night</night_icon>
</condition>
</codes>
如何编写函数,那将仅通过代码响应描述
作为一个功能(395)用雷霆@
返回@Moderate或大雪区域答案 0 :(得分:0)
一种简单的方法是使用正则表达式来提取值。它快速而有效(为什么将所有内容解析到内存中(dom)。
public static String extractDescription(String code, String xmlData){
//search for the entire condition element based on the id
Pattern elementPattern=Pattern.compile("<condition><code>"+code+"</code><description>(.*?)</description>.*</condition>");
Matcher elementMatcher=elementPattern.matcher(xmlData);
if(elementMatcher.groupCount()>0){//if we have some groups to match in our pattern
if(elementMatcher.find()){//find the matches
return elementMatcher.group(1);
}
else{//no match found
return null;
}
}
else{//our pattern is useless and does not contain any groups to match
return null;
}
}
这里唯一重要的操作是Pattern.compile(..),但它仍然非常快。
答案 1 :(得分:0)
您可以使用以下XPath:
/codes/condition[code='395']/description/text()
以下是在java中使用XPath的示例:http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html