2016-12-29 54 views
0

我有一個XMLAndroid的XML得到節點null值

<DatosClientes> 
    <User>Prueba</User> 
    <intUserNumber>1487</intUserNumber> 
    <IdUser>1328</IdUser> 
</DatosClientes> 

如何在Android中讀取數據?運行節點值的所有時間返回NULL時

public static void Parse(String response){ 
    try{ 
     DocumentBuilderFactory dbf = DocumentBuilderFactory 
       .newInstance(); 

     DocumentBuilder db = dbf.newDocumentBuilder(); 
     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(response)); 

     Document doc = db.parse(is); 
     doc.getDocumentElement().normalize(); 

     NodeList datos = doc.getElementsByTagName("DatosClientes"); 

     XmlParse parser = new XmlParse(); 

     for (int i = 0; i < datos.getLength(); i++) { 


      Node node = datos.item(i); 
      Element fstElmnt = (Element) node; 
      NodeList nameList = fstElmnt.getElementsByTagName("User"); 

      Log.e("log",String.valueOf(nameList.item(0).getNodeValue())); 
     } 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 


} 

我objetive終於讀值,轉換成ArrayList的

回答

0

這聽起來像你正試圖獲得在XML中值的列表?也就是說,你想:

{ "Prueba", "1487", "1328" } 

對於這一點,你可以這樣做:

public static final String XML_CONTENT = 
    "<DatosClientes>" 
    + "<User>Prueba</User>" 
    + "<intUserNumber>1487</intUserNumber>" 
    + "<IdUser>1328</IdUser>" 
    + "</DatosClientes>"; 

public static final Element getRootNode(final String xml) { 
    try { 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(new InputSource(new StringReader(xml))); 

     return document.getDocumentElement(); 
    } catch (ParserConfigurationException | SAXException | IOException exception) { 
     System.err.println(exception.getMessage()); 
     return null; 
    } 
} 

public static final List<String> getValuesFromXml(final String xmlContent) { 
    Element root = getRootNode(xmlContent); 
    NodeList nodes = root.getElementsByTagName("*"); 
    List<String> values = new ArrayList<>(); 

    for (int index = 0; index < nodes.getLength(); index++) { 
     final String nodeValue = nodes.item(index).getTextContent(); 
     values.add(nodeValue); 
     System.out.println(nodeValue); 
    } 

    return values; 
} 

public static void main (String[] args) { 
    final List<String> nodeValues = getValuesFromXml(XML_CONTENT); 
}