Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific XML elements with specific attribute value?

I am trying to parse an XML file from a URL by taking all "<Type>" elements where is parameter type_id="4218"??

XML document:

<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> 

Here is my Java code:

 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);    }  } 

This code gives me all elements, I don't want that, I want all elements where the attribute type_id = "4218"!

like image 701
dusmanka Avatar asked Dec 09 '11 12:12

dusmanka


People also ask

What is attr in XML?

The Attr object represents an attribute of an Element object. The allowable values for attributes are usually defined in a DTD. Because the Attr object is also a Node, it inherits the Node object's properties and methods.


1 Answers

XPath is right choice for you:

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); 

And iterate through nl

like image 82
korifey Avatar answered Sep 22 '22 05:09

korifey