xpath 介绍
项目应用
项目中webservice接口接收xml字符串参数,使用xpath
解析
<!--XML模板-->
<building>
<sellProject></sellProject> <!--销售项目-->
<number></number> <!--楼栋编码-->
<name></name> <!--楼栋名称-->
<subarea></subarea> <!--所属分区-->
<units><!--单元分录-->
<seq></seq> <!--单元序号-->
<name></name> <!--单元名称-->
<number></number> <!--单元编码-->
<description></description> <!--单元描述-->
</units>
</building>
**注意:XML传输格式中不允许带有“<!---->”注释片段,不然解析后台代码DocumentBuilder 转换为Document时不会报错**
// java使用xpath解析XML后台代码
InputStream is = new ByteArrayInputStream(syncData.getBytes("UTF-8")); // 将字符串转化为字符流
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();
Document document = documentBuilder.parse(is);
XPathFactory factory = XPathFactory.newInstance(); // 创建XPathFactory
XPath xPath = factory.newXPath(); // 用这个工厂创建 XPath对象
// 获取building下所有节点
NodeList nodeList = (NodeList)xPath.evaluate("building", document, XPathConstants.NODESET);
for(int i =0;i<nodeList.getLength();i++){
Node item = nodeList.item(i);
/*Element element =(Element)item;
NamedNodeMap attributes = item.getAttributes();*/
String sellProject = (String)xPath.evaluate("sellProject", item, XPathConstants.STRING);
checkThis("sellProject",sellProject);// 校验节点值是否为空
String name = (String)xPath.evaluate("name", item, XPathConstants.STRING);
NodeList roomModels = (NodeList)xPath.evaluate("building/roomModels", document, XPathConstants.NODESET);
for(int j = 0; j<roomModels.getLength();j++){
Node roomItem = roomModels.item(j);
String roomName = (String)xPath.evaluate("name", roomItem, XPathConstants.STRING);
checkThis("roomName",roomName);
String roomNumber = (String)xPath.evaluate("number", roomItem, XPathConstants.STRING);
checkThis("roomNumber",roomNumber);
String roomModelType = (String)xPath.evaluate("roomModelType", roomItem, XPathConstants.STRING);
checkThis("roomModelType",roomModelType);
}
}