Poldz Kerk
Poldz Kerk

Reputation: 69

Getting the information from xml from inpustream java

I have this program that read the xml from the inputstream and this is the xml that was the result of the inputStream

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
    <GetRouteSummaryForStopResponse xmlns="http://octranspo.com">
        <GetRouteSummaryForStopResult>
            <StopNo xmlns="http://tempuri.org/">string</StopNo>
            <StopDescription 
             xmlns="http://tempuri.org/">string</StopDescription>
            <Error xmlns="http://tempuri.org/">string</Error>
            <Routes xmlns="http://tempuri.org/">
                <Route>
                    <RouteNo>int</RouteNo>
                    <DirectionID>int</DirectionID>
                    <Direction>string</Direction>
                    <RouteHeading>string</RouteHeading>
                </Route>
                <Route>
                    <RouteNo>int</RouteNo>
                    <DirectionID>int</DirectionID>
                    <Direction>THIS IS A STRING</Direction>
                    <RouteHeading>string</RouteHeading>
                </Route>
            </Routes>
        </GetRouteSummaryForStopResult>
    </GetRouteSummaryForStopResponse>
</soap:Body>
</soap:Envelope>

I dont know where to start to get the Direction information that is in the xml.

public String HTTPrequest(String stopNo){
    String parameterURL = "appID="+this.appId+"&apiKey="+this.AppKey+"&routeNo=1&stopNo="+stopNo+"";    
    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.requestGetRouteSummaryForStop);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(parameterURL.getBytes().length));
        connection.setUseCaches (false);

        //send request
         DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
                  wr.writeBytes (parameterURL);
                  wr.flush ();
                  wr.close ();

        //Get Response  

          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer(); 
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
          }
          rd.close();
          System.out.print(response.toString());
      return response.toString();
    } catch (Exception e) {
        System.out.print("ERROR: ");
        e.printStackTrace();
        return null;
    }finally{
        if(connection != null){
            connection.disconnect();
        }
    }
}


public void parseXmlData(String response){
    InputSource xmlSource = new InputSource(new StringReader(response));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(xmlSource);

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();

        String routeHeading = xPath.evaluate("/GetRouteSummaryForStopResponse/GetRouteSummaryForStopResult/Routes/Route/Direction",document);
        System.out.print("RouteHeading: "+ routeHeading);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is the code for parsing the xml and connecting to the host

___________________:EDIT:_____________________

    public InputStream HTTPrequest(String stopNo){
    String parameterURL = "appID="+this.appId+"&apiKey="+this.AppKey+"&routeNo=1&stopNo="+stopNo+"";    
    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.requestGetRouteSummaryForStop);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(parameterURL.getBytes().length));
        connection.setUseCaches (false);

        //send request
         DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
                  wr.writeBytes (parameterURL);
                  wr.flush ();
                  wr.close ();

        //Get Response  

          InputStream is = connection.getInputStream();
         return is;
    } catch (Exception e) {
        System.out.print("ERROR: ");
        e.printStackTrace();
        return null;
    }finally{
        if(connection != null){
            connection.disconnect();
        }
    }
}


public void parseXmlData(InputStream response){
    InputStream is = response;

    try {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        Document doc = dbf.newDocumentBuilder().parse(is);

        XPathFactory xf = XPathFactory.newInstance();
        XPath xPath = xf.newXPath();

        // Find direction ANY where within the document...

        XPathExpression xExp = xPath.compile("//DirectionID");
        NodeList nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
        for (int index = 0; index < nl.getLength(); index++) {
            Node node = nl.item(index);
            System.out.println(node.getTextContent());
        }

        // Find the direction node's any where in the document
        // where it's a child of Route, which has a child
        // node called RouteNo with the text value of 'int'...
        xExp = xPath.compile("//Route[RouteNo = 'int']/Direction");
        nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
        for (int index = 0; index < nl.getLength(); index++) {
            Node node = nl.item(index);
            System.out.println(node.getTextContent());
        }

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}

it give me an error of

[Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at OcTranspoConnect.parseXmlData(OcTranspoConnect.java:82)
    at OcTranspoConnect.main(OcTranspoConnect.java:29)

Upvotes: 1

Views: 9362

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347244

You have two choices to start with...

You can

Load the XML into a Document Object Model. This allows you complete access to the XML to query it (and potentially modify it).

This is good if you need to do multiple pass of processing or want to make multiple queries into the data as the DOM is loaded into memory and is always available.

It's not so good if the XML file is large, as the DOM requires a fair amout of memory

A DOM approach provides you with the ability to use XPath support. XPath is a query API for XML (and can even be used for well structured HTML)

See Document Object Model for more detils.

You can

Process the XML document as it's being loaded by using a SAX parser. This provides callback methods/events that get called when something within the parsing processes raises them.

This is good when the document is large or you only need to do a single processing pass of the document (such as building your own object representation of the document for example).

It's not well suited for multiple pass processing or interactive querying.

Take a look at Simple API for XML for more details

Updated with XPath example

While I'm sure it's easy enough to deal with namespacing, to me, it just gets in the way.

The following is simple example of two XPath queries the finds all the Direction nodes within the document from you question

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathTest {

    public static void main(String[] args) {

        InputStream is = null;

        try {
            is = new FileInputStream("Soap.xml");

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(false);
            Document doc = dbf.newDocumentBuilder().parse(is);

            XPathFactory xf = XPathFactory.newInstance();
            XPath xPath = xf.newXPath();

            // Find direction ANY where within the document...

            XPathExpression xExp = xPath.compile("//Direction");
            NodeList nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
            for (int index = 0; index < nl.getLength(); index++) {
                Node node = nl.item(index);
                System.out.println(node.getTextContent());
            }

            // Find the direction node's any where in the document
            // where it's a child of Route, which has a child
            // node called RouteNo with the text value of 'int'...
            xExp = xPath.compile("//Route[RouteNo = 'int']/Direction");
            nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
            for (int index = 0; index < nl.getLength(); index++) {
                Node node = nl.item(index);
                System.out.println(node.getTextContent());
            }

        } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException exp) {
            exp.printStackTrace();
        }
    }
}

This outputs...

string
THIS IS A STRING
string
THIS IS A STRING

Upvotes: 3

Related Questions