PDA

View Full Version : [Java] Leggere file Xml


GiulioCesare
16-12-2005, 13:22
Salve ragazzi, sto cercando di leggere un file xml, tramite java, ma ho dei problemi, ho fatto due metodi che leggono dalla radice del file, ed a secondo dell'element che viene passato leggono il relativo valore, perņ invece di ritornare il valore giusto, ritorna un valore nullo. Posto di seguito i due metodi che ho fatto, e poi il mio file xml da leggere, con la speranza che qualcuno mi aiuti

public String getParam(String paramname)
{
//get the root elememt
Element docEle = dom.getDocumentElement();
String retparam = null;
NodeList nl = docEle.getElementsByTagName("radice");

if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
Element el = (Element)nl.item(i);
retparam = getTextValue(el,paramname);
}
}
return retparam;
}

public String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
if(textVal.equals(null)) textVal = "";
return textVal;
}


File XML
<?xml version="1.0" encoding="UTF-8"?>
<radice>
<driver_db>Valore</driver_db>
<url_db>Valore</url_db>
<user_db>Valore</user_db>
<path_dest_xml>Valore</path_dest_xml>
<tipo_db>Valore</tipo_db>
</radice>

sottovento
19-12-2005, 11:53
Ciao,
da quello che ho capito, il problema e' che dai per scontato che il primo nodo, sotto a quello che passi per parametro, sia il #text. Prova a controllarlo esplicitamente.
Magari per prova, nella getTextValue(), stampali tutti. Immagino lo troverai facilmente

High Flying
Sottovento

pipozzolo
21-12-2005, 15:28
public String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = ((Text)el.getFirstChild()).getData();
}
if(textVal.equals(null)) textVal = "";
return textVal;
}



prova con questo