一. 背景知识:
今天在做项目的时候遇到这样一个需求:使用http请求公司内部一个网站,返回xml数据,然后解析xml数据从而判断产品是否已经上线。其实这个非常简单,使用dom解析就ok了。
二. 上传xml数据:
上传students.xml文件到服务器
<?xml version="1.0" encoding="utf-8"?>
<students>
<student id="1">
<name>张三</name>
<phoneno>13520845073</phoneno>
</student>
<student id="2">
<name>李四</name>
<phoneno>18934569843</phoneno>
<login>true</login>
</student>
<student id="3">
<name>王五</name>
<phoneno>13673986274</phoneno>
</student>
</students>
三. 创建一个对象来封装数据:
public class Student {
private int id;
private String name;
private String phone;
// getter and setter
}
四. 使用dom解析xml数据:
public class DomService {
public static void main(String[] args) {
String path = "http://localhost/students.xml";
InputStream input = getInputStream(path);
DomService service = new DomService();
try {
List<Student> list = service.getStudents(input);
for (Student student : list) {
System.out.println(student.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取xml输入流
public static InputStream getInputStream(String path) {
InputStream inputStream = null;
try {
URL url = new URL(path);
if (url != null) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000); // 设置超时时间为3秒
connection.setDoInput(true);
connection.setRequestMethod("GET"); // 设置请求方式
int code = connection.getResponseCode(); // 接受返回码
if (200 == code) { // 返回码为200为成功
inputStream = connection.getInputStream();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return inputStream;
}
// 将XML转换为对象
public List<Student> getStudents(InputStream inputStream) throws Exception {
List<Student> list = new ArrayList<Student>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 创建一个Document解析工厂
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream); // 将输入流解析为Document
Element element = document.getDocumentElement(); // 整个文档就是一个节点文档
NodeList nodeList = element.getElementsByTagName("student"); // 获取所有student节点,并进行遍历
for (int i = 0; i < nodeList.getLength(); i++) {
Student student = new Student();
Element e = (Element) nodeList.item(i); // 获取具体的一个student节点
student.setId(Integer.parseInt(e.getAttribute("id")));
NodeList childNodes = e.getChildNodes(); // 获取student节点下的所有子节点,并进行遍历
for (int j = 0; j < childNodes.getLength(); j++) {
if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) { // 如果该节点是元素节点
if ("name".equals(childNodes.item(j).getNodeName())) {
student.setName(childNodes.item(j).getFirstChild().getNodeValue());
} else if ("phoneno".equals(childNodes.item(j).getNodeName())) {
student.setPhone(childNodes.item(j).getFirstChild().getNodeValue());
}
}
}
list.add(student); // 添加student对象到集合
}
return list;
}
}
五. 测试结果:
Student [id=1, name=张三, phone=13520845073]
Student [id=2, name=李四, phone=18934569843]
Student [id=3, name=王五, phone=13673986274]