gpt4 book ai didi

java - Android xml获取节点值null

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:02 25 4
gpt4 key购买 nike

我有一个 xml

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


}

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

最佳答案

听起来您正在尝试获取 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);
}

关于java - Android xml获取节点值null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com