猿问

如何在 Java 中解析字符串 XML

我有一个字符串 XML。我需要从 Java 中的 XML获取项目ISSUCCESS值。但项目值返回空值。这是我的 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);

}


侃侃无极
浏览 159回答 3
3回答

幕布斯7119047

ISSUCCESS 是一个元素而不是一个属性。改成:NodeList nodeList = doc.getElementsByTagName("QRYRESULT");for (int i = 0; i < nodeList.getLength(); i++) {&nbsp; &nbsp; Element value = (Element) nodeList.item(i);&nbsp; &nbsp; String ISSUCCESS = value.getElementsByTagName("ISSUCCESS").item(0).getTextContent();&nbsp; &nbsp; System.out.println("ISSUCCESS = " + ISSUCCESS);}

MYYA

DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();InputSource is = new InputSource();is.setCharacterStream(new StringReader(**myXML**));Document doc = db.parse(is);NodeList nodes = doc.getElementsByTagName("QRYRESULT");Element qryresult = (Element) nodes.item(0);Element success = (Element) qryresult.getElementsByTagName("ISSUCCESS").item(0);String iSuccess=success.getFirstChild().getTextContent();System.out.println("ISSUCCESS: " + iSuccess);

翻过高山走不出你

试试这个。DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document doc = db.parse(contactsXMLstream);doc.getDocumentElement().normalize();NodeList nList = doc.getElementsByTagName("QRYRESULT");entries=new MarketEntry[nList.getLength()];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;for (int temp = 0; temp < nList.getLength(); temp++){&nbsp; &nbsp; Node nNode = nList.item(temp);&nbsp; &nbsp; if (nNode.getNodeType() == Node.ELEMENT_NODE)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Element eElement = (Element) nNode;&nbsp; &nbsp; &nbsp; &nbsp; String vr= eElement.getElementsByTagName("ISSUCCESS").item(0).getTextContent();&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答