2011-12-09 15 views
25

Estoy tratando de analizar un archivo XML desde una URL tomando todos los elementos "<Type>" donde está el parámetro type_id = "4218" ??¿Cómo obtener elementos XML específicos con un valor de atributo específico?

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

Aquí está mi código 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); 
    } 
} 

Este código me da todos los elementos, no quiero eso, quiero que todos los elementos donde el atributo type_id = "4218"!

Respuesta

23

XPath es la elección correcta para usted:

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

Y recorrer nl

+0

¿Cómo puedo buscar el valor en TYPE_ID con el operador como –

4

Puede usar XPath.XPath se utiliza para navegar a través de elementos y atributos en un documento XML. Hay algunas buenas implementaciones de Xpath en Java.

Por ejemplo, se

XPath xpath = XPathFactory.newInstance().newXPath(); 
XPathExpression expr = xpath.compile("//Type[@type_id=\"4218\"]"); 
Object exprResult = expr.evaluate(doc, XPathConstants.NODESET); 
NodeList nodeList = (NodeList) exprResult; 
7

Te estás perdiendo una condición dentro de su bucle:

if(nodeList != null && nodeList.getLength() > 0){ 
    for (int j = 0; j < nodeList.getLength(); j++) { 
     Element el = (org.w3c.dom.Element) nodeList.item(j); 
     if (el.hasAttribute("type_id") && el.getAttribute("type_id").equals("4218")) { 
       type_id = Integer.parseInt(el.getAttribute("type_id")); 

       System.out.println("type id:"+type_id); 
     } 
    } 
} 

también que no es necesario probar si NodeList devuelto por getElementsByTagName es nulo para que pueda quitar el si antes del bucle.

En general, es posible que sea mejor utilizar XPath.

2

La siguiente XPath le dará los elementos del tipo que está buscando:

/BSQCUBS/Class/Type[@type_id=4218] 

para que pueda usar el siguiente código Java para obtener una NodeList que solo incluye estos:

XPathExpression expr = xpath.compile("/BSQCUBS/Class/Type[@type_id=4218]"); 
NodeList nl = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); 
2

sigue @soulcheck responde a continuación y escribe una declaración de interrupción si es posible ... que podría mejorar tu búsqueda.

if(nodeList != null && nodeList.getLength() > 0){ 
for (int j = 0; j < nodeList.getLength(); j++) { 
    Element el = (org.w3c.dom.Element) nodeList.item(j); 
    if (el.hasAttribute("type_id") && el.getAttribute("type_id").equals("4218")) { 
      type_id = Integer.parseInt(el.getAttribute("type_id")); 

      System.out.println("type id:"+type_id); 
      break; 

    } 
} 

}

Cuestiones relacionadas