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

72 views Asked by At

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!

1

There are 1 answers

0
Keaton Proctor On

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 the responseDoc Document object instead of the reqestDoc Document object. Each of those objects had a different XML, and in the requestDoc, there was no element inside named <status>.