我在这个一般领域看到了一些问题,但找不到任何特定于 Java 和提取单个节点值的问题。
我有一个返回值格式如下的 Web 服务:
<string xmlns="http://tempuri.org/">Hello</string>
在 Android 应用程序中,我试图在没有 XML
标记的情况下检索中间的“Hello”部分。
我目前有这样的方法来做到这一点:
public static String getParsedString(String xml)
{
try
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource input = new InputSource();
StringReader stringReader = new StringReader(xml);
input.setCharacterStream(stringReader);
Document document = documentBuilder.parse(input);
NodeList nodes = document.getElementsByTagName("string");
return nodes.item(0).getNodeValue().toString();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
然而,正在解析的节点显然不包含任何数据,因为在尝试 toString()
方法时,它会抛出以下错误。
java.lang.NullPointerException
我不确定我是否需要考虑文档解析器中的 xmlns="http://tempuri.org/"
,但我想不通。
最佳答案
换行
return nodes.item(0).getNodeValue().toString();
到
return nodes.item(0).getTextContent();
关于java - 从 Web 服务响应中解析单个 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42248973/