简体   繁体   中英

Android xml get node value null

i have a xml

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

How to read data in android ? when run all time return null in node value

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


}

my objetive is finally read value and convert into ArrayList

It sounds like you are trying to get a list of the values in the XML? That is, you want:

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

For that, you can do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM