dom4j解析带命名空间的xml文件

时间:2023-03-09 00:34:38
dom4j解析带命名空间的xml文件

文件内容如下

<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://WebXml.com.cn/">
<string>浙江</string>
<string>杭州</string>
<string>58457</string>
<string>58457.jpg</string>
<string>2016-3-22 17:57:12</string>
<string>11℃/16℃</string>
<string>3月22日 阵雨</string>
<string>东南风微风</string>
<string>3.gif</string>
<string>3.gif</string>
<string>今日天气实况:气温:13℃;风向/风力:南风 1级;湿度:81%;紫外线强度:弱。空气质量:良。</string>
<string>
紫外线指数:弱,辐射较弱,涂擦SPF12-15、PA+护肤品。 感冒指数:较易发,天凉,湿度大,较易感冒。 穿衣指数:较冷,建议着厚外套加毛衣等服装。 洗车指数:不宜,有雨,雨水和泥水会弄脏爱车。
运动指数:较不宜,有降水,推荐您在室内进行休闲运动。 空气污染指数:良,气象条件有利于空气污染物扩散。
</string>
<string>6℃/12℃</string>
<string>3月23日 阵雨转阴</string>
<string>东北风3-4级</string>
<string>3.gif</string>
<string>2.gif</string>
<string>5℃/13℃</string>
<string>3月24日 多云</string>
<string>北风3-4级</string>
<string>1.gif</string>
<string>1.gif</string>
<string>
杭州市是浙江省省会,国务院确定的全国重点风景旅游城市和历史文化名城,位于北纬30°16’、东经120°12’,地处长江三角洲南翼,杭州湾西端,钱塘江下游,京杭大运河南端,东濒杭州湾、钱塘江,南与金华市、衢州市、绍兴市相接,西与安徽省黄山市交界,北与湖州市、嘉兴市相邻。下辖8个区、5个县(市),全市总面积16596平方千米,其中市区面积3068平方千米。改革开放以来,杭州经济发展迅猛,2007年全市实现国内生产总值4103.89亿元,人均GDP达8063美元,连续17年保持2位数增长,连续4年被誉为“中国最具幸福感的城市”。
杭州尤以西湖秀丽迷人的自然风光闻名于世。美丽的西湖三面环山,一面濒城,两堤卧波,三岛浮水,风景秀丽,四季异色,古迹珠连,名人荟萃,历代诗人吟咏不绝。杭州自然景观和人文景观十分丰富,文物、古迹众多,古代庭、园、楼、阁、塔、寺、泉、壑、石窟、摩崖碑刻遍布,众多景点或诡异神秘、内蕴深沉,或珠帘玉带、烟柳画桥,或万千姿态、蔚然奇观,或山青水秀、风情万般。全市现有60多个对外开放景点和40多处重点文物保护单位,以灵隐寺、六和塔、飞来峰、岳庙、西泠印社、三潭印月、花港观鱼、龙井、虎跑等最为著名。
</string>
</ArrayOfString> <!--
根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
调用方法如下:输入参数:theCityName = 城市中文名称(国外城市可用英文)或城市代码(不输入默认为上海市),如:上海 或 58367,如有城市名称重复请使用城市代码查询(可通过 getSupportCity 或 getSupportDataSet 获得);返回数据: 一个一维数组 String(22),共有23个元素。
String(0) 到 String(4):省份,城市,城市代码,城市图片名称,最后更新时间。String(5) 到 String(11):当天的 气温,概况,风向和风力,天气趋势开始图片名称(以下称:图标一),天气趋势结束图片名称(以下称:图标二),现在的天气实况,天气和生活指数。String(12) 到 String(16):第二天的 气温,概况,风向和风力,图标一,图标二。String(17) 到 String(21):第三天的 气温,概况,风向和风力,图标一,图标二。String(22) 被查询的城市或地区的介绍
下载天气图标(包含大、中、小尺寸) 天气图例说明 调用此天气预报Web Services实例下载 (VB ASP.net 2.0)-->

注意,该xml是带命名空间的!!!

如果这份xml是一份本地文件,可以用以下方法:

@Test
public void convertTest(){
try {
//File directory = new File("");//设定为当前文件夹
//directory.getCanonicalPath()
SAXReader reader = new SAXReader();
Document document = reader.read(new File(
"src\\test\\java\\com\\hikvision\\ibms\\indexconfig\\runtime\\engine" +
"\\weather.xml"));
//法一
String t=document.asXML();
System.out.println("读取完毕:"+"\n"+t);
Element rootElm = document.getRootElement();
System.out.println(rootElm.getName());
List nodes = rootElm.elements("string");
System.out.println("第一种方法读元素string的个数为:"+nodes.size());
//法二
HashMap map = new HashMap();
map.put("design",rootElm.getNamespaceURI());
// 创建解析路径,就是在普通的解析路径前加上map里的key值
XPath xPath = document.createXPath("//design:ArrayOfString/design:string");
xPath.setNamespaceURIs(map);
List nodes2 = xPath.selectNodes(document);
System.out.println("第二种方法读取元素string的个数为:"+nodes2.size());
} catch (Exception e) {
e.printStackTrace();
}
}

dom4j解析带命名空间的xml文件

如果是基于webservice,远程读取文件的话,可以使用:

package endpoint;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; /**
* 类作用调用webservice得到天气预报服务
*/
public class Weather {
/**
* 获取soap请求头,并替换其中的标志符号为用户的输入符号
* @param city 用户输入城市名
* @return 用户将要发送给服务器的soap请求
*/
private static String getSoapRequest(String city) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body> <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"
+ "<theCityName>" + city
+ "</theCityName> </getWeatherbyCityName>"
+ "</soap:Body></soap:Envelope>");
return sb.toString();
}
/**
* 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流
* @param city 用户输入的城市名称
* @return 服务器端返回的输入流,供客户端读取
* @throws Exception
*/
public static InputStream getSoapInputStream(String city) throws Exception {
try {
String soap = getSoapRequest(city);
if (soap == null) {
return null;
}
URL url = new URL(
"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(soap
.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("SOAPAction",
"http://WebXml.com.cn/getWeatherbyCityName");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
osw.write(soap);
osw.flush();
osw.close();
InputStream is = conn.getInputStream();
//System.out.println(is.toString());
return is;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 通过dom4j对服务器端返回的XML进行解析
* @param city 用户输入的城市名称
* @return 符串 用,分割
*/
public static String getWeather(String city) {
Document document=null;
SAXReader reader = new SAXReader();
String s="";
Map map=new HashMap();
map.put("design", "http://WebXml.com.cn/");
reader.getDocumentFactory().setXPathNamespaceURIs(map);
try {
InputStream is = getSoapInputStream(city);//得到输入流
document=reader.read(is);//将输入流转化为document
String t=document.asXML();
} catch (Exception e) {
e.printStackTrace();
}
List nodes = document.selectNodes("//design:string");
for (Iterator it = nodes.iterator(); it.hasNext();) {
Element elm = (Element) it.next();
String text=elm.getText();
//System.out.println("fsffs"+text);
s=s+elm.getText()+"\n";
}
return s;
}
/**
* 测试函数
* @param args
*/
public static void main(String args[]){
Weather w=new Weather();
System.out.println(w.getWeather("杭州"));
}
}