java - 如何获取具有特定属性值的特定 XML 元素?

标签 java xml-parsing

我正在尝试通过获取所有“<Type>”元素来解析来自 URL 的 XML 文件,其中参数 type_id="4218"??

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"的所有元素!

最佳答案

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

关于java - 如何获取具有特定属性值的特定 XML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445408/

相关文章:

java - 组合键在 Ubuntu 中不起作用

java - Android RSS 示例

xml - Groovy XmlSlurper 访问根节点中的属性值

c# - 更改嵌套节点的内部文本并为其分配 C# 中父节点的第一个兄弟节点的值

java - http 服务器的 Netty 内存泄漏。什么时候发布消息?

java - tomcat WEB-INF 上的 jar 名称列表

java - 如果时间跨度重叠且小于 30 分钟,则对日志条目进行分组?

java - 使用数组列表提取数据时尝试在空对象引用上调用虚拟方法 'java.lang.String'

c - 如何在c中使用libxml2根据属性对xml文件进行分类

java - 解析XML类型文件