我有一个String XML。我需要从Java中的XML获取项目ISSUCCESS值。但是项目值返回null。这是我的XML代码。
XML格式
<QRYRESULT><ISSUCCESS>N</ISSUCCESS><REASON>E002</REASON><WARNING>1. Transaction date Should be current date.11-SEP-18 E </WARNING></QRYRESULT>
我已经写了下面的代码来获取ISSUCCESS项目的值。
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(**myXML**));
Document doc = db.parse(is);
NodeList nodeList = doc.getElementsByTagName("QRYRESULT");
for (int i = 0; i < nodeList.getLength(); i++) {
Element value = (Element) nodeList.item(i);
String ISSUCCESS = value.getAttribute("ISSUCCESS");
System.out.println("ISSUCCESS = " + ISSUCCESS);
}
最佳答案
ISSUCCESS是元素而不是属性。
改成:
NodeList nodeList = doc.getElementsByTagName("QRYRESULT");
for (int i = 0; i < nodeList.getLength(); i++) {
Element value = (Element) nodeList.item(i);
String ISSUCCESS = value.getElementsByTagName("ISSUCCESS").item(0).getTextContent();
System.out.println("ISSUCCESS = " + ISSUCCESS);
}