XPath解析属性、节点内容及遍历子节点
2016-01-08 17:02
573 查看
String xml = "<?xml version='1.0' encoding='UTF-8'?>" + "<definition id=\"26743\">" + " <metadata>" + " <title>AIX OpenSSL Denial of Service...</title>" + " <affected family=\"unix\">" + " <platform>IBM AIX 6.1</platform>" + " <platform></platform>" + " <platform>IBM AIX 7.1</platform>" + " </affected>" + " </metadata>" + "</definition>"; Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(xml.getBytes("UTF-8"))); XPath xpath = XPathFactory.newInstance().newXPath(); /* 1、取节点属性 */ String id = (String) xpath.evaluate( "/definition/attribute::id", document, XPathConstants.STRING); System.out.println(id); String family = (String) xpath.evaluate( "/definition/metadata/affected/attribute::family", document, XPathConstants.STRING); System.out.println(family); /* 2、取节点文本内容 */ String title = (String) xpath.evaluate( "/definition/metadata/title/text()", document, XPathConstants.STRING); System.out.println(title); /* 3、遍历子节点取文本 */ //方法1 通过document取子节点个数 /*int len = document.getElementsByTagName("affected").item(0).getChildNodes().getLength();*/ //方法2 通过xpath取子节点集合 /*NodeList nodeSet = (NodeList)xpath.evaluate( "/definition/metadata/affected/platform", document, XPathConstants.NODESET); int len = nodeSet.getLength();*/ //方法3 通过count函数取子节点个数 int len = Integer.parseInt(xpath.evaluate( "count(/definition/metadata/affected/platform)", document, XPathConstants.STRING).toString()); for (int i = 1; i <= len; i++) { String platform = (String) xpath.evaluate( "/definition/metadata/affected/platform[" + i + "]/text()", document, XPathConstants.STRING); System.out.println(platform); }
相关文章推荐
- 把网站链接卖一个好价钱: Text Link Ads 注册网赚攻略
- MSSQL数据库获取TEXT字段的内容长度
- 『jQuery』.html(),.text()和.val()的概述及使用
- C#通过xpath查找xml指定元素的方法
- ASP中获得Select Count语句返回值的方法
- 点击button获取text内容并改变样式的js实现
- JQuery中Text方法用法实例分析
- jQuery获取Select选择的Text和Value(详细汇总)
- jQuery操作Select选择的Text和Value(获取/设置/添加/删除)
- firefox下获取下列框选中option的text的代码
- mysql_num_rows VS COUNT 效率问题分析
- JS获取下拉列表所选中的TEXT和Value的实现代码
- js获取TreeView控件选中节点的Text和Value值的方法
- mssql查找备注(text,ntext)类型字段为空的方法
- 对text数据类型不支持代码页转换 从: 1252 到: 936
- PHP源代码数组统计count分析
- xpath的数据和节点类型以及XPath中节点匹配的基本方法
- c#通过xpath读取xml示例
- JQuery 选择器 xpath 语法应用