简体   繁体   中英

Trying to get the normal text between an opening and closing element tag

I am trying to get just the text printed out between one specific element tag in an XML file. Here is my java code:

    SAXBuilder builder = new SAXBuilder();

byte[] requestFile = FileManager.getByteArray(args[0]);
byte[] responseFile = FileManager.getByteArray(args[1]);

InputStream request = new ByteArrayInputStream(requestFile);
InputStream response = new ByteArrayInputStream(responseFile);
        
Document requestDoc = builder.build(request);
Document responseDoc = builder.build(response);
    
String xpathResponseStr = "//status";
JDOMXPath xpath = new JDOMXPath(xpathResponseStr);
Element responseElem = (Element)xpath.selectSingleNode(requestDoc);
String statusRequestText = responseElem.getTextTrim();
    
System.out.println("RESPONSE: \n" + statusRequestText);

And here is my XML file that I am reading in:

  <status>success</status>
  <generatedDate>
    <date>2022-09-08</date>
    <time>12:03:23</time>
  </generatedDate>

  <filingInformation>
    <paymentInformation>
      <amount>0.00</amount>
    </paymentInformation>
  </filingInformation>

</response>

I am essentially trying to get my console to print the word "success" between the tags. But instead I am getting a null pointer. Not sure if this is because my xpath expression is incorrect or what exactly. Any input would help!

What I was doing wrong was I was calling the wrong Document object when running

"Element responseElem = (Element)xpath.selectSingleNode(requestDoc);"

It should have been passing in a the responseDoc Document object instead of the reqestDoc Document object. Each of those objects had different XML, and in the requestDoc, there was no element inside named.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM