如何解决如何获得具有特定属性值的特定XML元素?
XPath是您的正确选择:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("<Your xml doc uri>");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//Type[@type_id=\"4218\"]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
并遍历 nl
解决方法
我试图通过将所有<Type>
参数元素为type_id =“ 4218”的所有“ ”元素从URL解析XML文件?
XML文件:
<BSQCUBS Version="0.04" Date="Fri Dec 9 11:43:29 GMT 2011" MachineDate="Fri,09 Dec 2011 11:43:29 +0000">
<Class class_id="385">
<Title>Football Matches</Title>
<Type type_id="4264" type_minbet="0.1" type_maxbet="2000.0">
...
</Type>
<Type type_id="5873" type_minbet="0" type_maxbet="0">
...
</Type>
<Type type_id="4725" type_minbet="0.1" type_maxbet="2000.0">
...
</Type>
<Type type_id="4218" type_minbet="0.1" type_maxbet="2000.0">
...
</Type>
<Type type_id="4221" type_minbet="0.1" type_maxbet="2000.0">
...
</Type>
<Type type_id="4218" type_minbet="0.1" type_maxbet="2000.0">
...
</Type>
<Type type_id="4299" type_minbet="0.1" type_maxbet="2000.0">
...
</Type>
</Class>
</BSQCUBS>
这是我的Java代码:
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL("http://cubs.bluesq.com/cubs/cubs.php?action=getpage&thepage=385.xml").openStream());
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Type");
System.out.println("ukupno:"+nodeList.getLength());
if (nodeList != null && nodeList.getLength() > 0) {
for (int j = 0; j < nodeList.getLength(); j++) {
Element el = (org.w3c.dom.Element) nodeList.item(j);
type_id = Integer.parseInt(el.getAttribute("type_id"));
System.out.println("type id:"+type_id);
}
}
这段代码给了我所有元素,我不想要,我想要属性type_id =“ 4218”的所有元素!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。