为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Java 中解析字符串 XML

如何在 Java 中解析字符串 XML

侃侃无极 2021-09-15 15:01:24
我有一个字符串 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);}
查看完整描述

3 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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

}


查看完整回答
反对 回复 2021-09-15
?
MYYA

TA贡献1868条经验 获得超4个赞

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


查看完整回答
反对 回复 2021-09-15
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

试试这个。


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

for (int temp = 0; temp < nList.getLength(); temp++)

{

    Node nNode = nList.item(temp);

    if (nNode.getNodeType() == Node.ELEMENT_NODE)

    {

        Element eElement = (Element) nNode;

        String vr= eElement.getElementsByTagName("ISSUCCESS").item(0).getTextContent();

    }

}


查看完整回答
反对 回复 2021-09-15
  • 3 回答
  • 0 关注
  • 158 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信