有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android xml获取节点值null

我有一个xml

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

如何在安卓中读取数据?当运行所有时间时,在节点值中返回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();
    }


}

我的目标是最终读取值并转换为ArrayList


共 (1) 个答案

  1. # 1 楼答案

    听起来像是在试图获取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);
    }