Search code examples
javaxmlparsingsaxstax

How to get a specific event/attribute content from an xml string via stAX or SAX


I have a xml POST response which I receive as a string. I need the content of the particular "pnr" (see in xml) to pass it on to another GET request. I am trying sax and stAX to achieve this but failing miserably. I used getElementsByTagName and also getAttribute, but no go... Here's my code and later the xml string that I receive.

Any kind of help will be a gift

package rest;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;


public class ParseXMLString {

  public static void main(String arg[]) {
    String outputString =  RESTClient.postConfirm(); // this is the xml string response I am getting

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(outputString));

        Document doc = db.parse(is);
        String Parentnode = doc.getDocumentElement().getAttribute("pnr");       
//           Element element = (Element) Parentnode.;
//           NodeList name = element.getElementsByTagName("pnr");
//           Element line = (Element) name.item(0);
           //String IDList = getCharacterDataFromElement(line);   
           System.out.println(Parentnode);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
       CharacterData cd = (CharacterData) child;
       return cd.getData();
    }
    return "?";
  }
}

And here is the the XML String I have received:

<?xml version="1.0" encoding="UTF-8"?><Ticket><bookedSeats>3</bookedSeats><bpAddress>Anand Rao Circle</bpAddress><bpLandMark>ganesha temple</bpLandMark><bpLocation> Ghousia College</bpLocation><bpPhoneNo>98798679769</bpPhoneNo><bpTime>1200</bpTime><busServiceName>efdf</busServiceName><busType>Volvo A/C Semi Sleeper (2+2)</busType><commission>66.19</commission><dateOfJourney>2012-10-05</dateOfJourney><destination>Chennai</destination><fare>600.0</fare><issueTime>2012-10-04T15:46:45.073+05:30</issueTime><noOfSeats>1</noOfSeats><passengerMobile>1234567890</passengerMobile><passengerName>Test</passengerName><pnr>RATPKES44974756</pnr><seatDetails><seatDetail><commission>66.19</commission><fare>600.0</fare><gender>MALE</gender><passengerAge>0</passengerAge><passengerMobile>1234567890</passengerMobile><passengerName>Test</passengerName><prime>false</prime><seatName>3</seatName></seatDetail></seatDetails><source>Bangalore</source><status>BOOKED</status><travelsName>Rajratan Travels</travelsName></Ticket>

Solution

  • Instead of SAX or StAX you could do the following with the javax.xml.xpath APIs in the JDK/JRE since Java SE 5:

    Demo

    import java.io.StringReader;
    import javax.xml.xpath.*;
    import org.xml.sax.InputSource;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            String xml = "<?xml version='1.0' encoding='UTF-8'?><Ticket><bookedSeats>3</bookedSeats><bpAddress>Anand Rao Circle</bpAddress><bpLandMark>ganesha temple</bpLandMark><bpLocation> Ghousia College</bpLocation><bpPhoneNo>98798679769</bpPhoneNo><bpTime>1200</bpTime><busServiceName>efdf</busServiceName><busType>Volvo A/C Semi Sleeper (2+2)</busType><commission>66.19</commission><dateOfJourney>2012-10-05</dateOfJourney><destination>Chennai</destination><fare>600.0</fare><issueTime>2012-10-04T15:46:45.073+05:30</issueTime><noOfSeats>1</noOfSeats><passengerMobile>1234567890</passengerMobile><passengerName>Test</passengerName><pnr>RATPKES44974756</pnr><seatDetails><seatDetail><commission>66.19</commission><fare>600.0</fare><gender>MALE</gender><passengerAge>0</passengerAge><passengerMobile>1234567890</passengerMobile><passengerName>Test</passengerName><prime>false</prime><seatName>3</seatName></seatDetail></seatDetails><source>Bangalore</source><status>BOOKED</status><travelsName>Rajratan Travels</travelsName></Ticket>";
    
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
    
            InputSource inputSource = new InputSource(new StringReader(xml));
            String pnr = (String) xpath.evaluate("/Ticket/pnr", inputSource, XPathConstants.STRING);
            System.out.println(pnr);
        }
    
    }
    

    Output

    RATPKES44974756