我有一个 XML
文件,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<coffeeOrder>
<addition>null</addition>
<cost>3.0</cost>
<id>1</id>
<links>http://localhost:9080/cs9322.ass2/rest/payment/1</links>
<status>cancelled</status>
<type>espresso</type>
</coffeeOrder>
我正在尝试检索状态
的值
。
目前我有以下内容:
try {
Document document = loadXMLFromString(orderXML);
NodeList nodeList = document.getDocumentElement().getChildNodes();
// Cycle through nodes, until "status" or "paymentType" element found
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) node;
System.out.println(orderXML);
System.out.println(elem.toString());
if (type.equals("order") && elem.getNodeName().equals("status")){
status = elem.getNodeValue();
} else if(type.equals("payment") && elem.getNodeName().equals("paymentType")){
status = elem.getNodeValue();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
但是,我发现我不断地得到null
。
System.out.println(elem.toString());
返回
[status: null]
尽管
System.out.println(orderXML);
显示状态
不为null
有人知道我在这里做错了什么吗?
最佳答案
使用getTextContent
方法而不是getNodeValue
。请参阅有关 Node
的文档类。
关于java - 获取 xml 中元素的值 - 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26438185/