2011-09-20 9 views
5

Sto usando il parser DOM di Java per analizzare un file XML.Documento - Come ottenere il valore di un tag in base al nome?

diciamo che ho il seguente XML

<?xml version="1.0"?> 

<config> 
    <dotcms> 
     <endPoint>ip</endPoint> 
    </dotcms> 
</config> 

</xml> 

mi piace per ottenere il valore di 'endpoint'. Posso farlo con il seguente frammento di codice. (Supponendo che ho già analizzato con DocumentBuilder)

NodeList nodeList = this.doc.getElementByTagName("dotcms"); 
Node nValue = (Node) nodeList.item(0); 
return nValue.getNodeValue(); 

E 'possibile ottenere un valore di un campo con il nome di un campo? Mi piace ....

Node nValue = nodeList.getByName("endPoint") qualcosa del genere ...?

risposta

5

Si dovrebbe usare XPath per questi tipi di compiti:

//endPoint/text() 

o:

/config/dotcms/endPoint/text() 

Naturalmente Java ha un built-in support per XPath:

XPath xpath = XPathFactory.newInstance().newXPath(); 
XPathExpression expr = xpath.compile("//endPoint/text()"); 
Object value = expr.evaluate(doc, XPathConstants.STRING); 
+0

// Grande !! Lo apprezzo! Risposta breve, ma utile. – Moon

0

È potrebbe anche utilizzare jOOX, un dominio DOM jquery per scrivere meno codice:

// Using css-style selectors 
String text1 = $(document).find("endPoint").text(); 

// Using XPath 
String text2 = $(document).xpath("//endPoint").text(); 
Problemi correlati