0

I get the xml repsonse for http request. I store it as a string variable

String str = in.readLine();

And the contents of str is:

<response>
    <lastUpdate>2012-04-26 21:29:18</lastUpdate>
    <state>tx</state>
    <population>
       <li>
           <timeWindow>DAYS7</timeWindow>
           <confidenceInterval>
              <high>15</high>
              <low>0</low>
           </confidenceInterval>
           <size>0</size>
       </li>
    </population>
</response>

I want to assign tx, DAYS7 to variables. How do I do that?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SUM
  • 1,651
  • 4
  • 33
  • 57

1 Answers1

0

Slightly modified code from http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

public class ReadXMLFile {

    // Your variables
    static String state;
    static String timeWindow;

    public static void main(String argv[]) {

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            // Http Response you get
            String httpResponse = "<response><lastUpdate>2012-04-26 21:29:18</lastUpdate><state>tx</state><population><li><timeWindow>DAYS7</timeWindow><confidenceInterval><high>15</high><low>0</low></confidenceInterval><size>0</size></li></population></response>";

            DefaultHandler handler = new DefaultHandler() {

                boolean bstate = false;
                boolean tw = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

                    if (qName.equalsIgnoreCase("STATE")) {
                        bstate = true;
                    }

                    if (qName.equalsIgnoreCase("TIMEWINDOW")) {
                        tw = true;
                    }

                }

                public void characters(char ch[], int start, int length) throws SAXException {

                    if (bstate) {
                        state = new String(ch, start, length);
                        bstate = false;
                    }

                    if (tw) {
                        timeWindow = new String(ch, start, length);
                        tw = false;
                    }
                }

            };

            saxParser.parse(new InputSource(new ByteArrayInputStream(httpResponse.getBytes("utf-8"))), handler);

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

        System.out.println("State is " + state);
        System.out.println("Time windows is " + timeWindow);
    }

}

If you're running this as a part of some process you might want to extend the ReadXMLFile from DefaultHandler.

ant
  • 22,634
  • 36
  • 132
  • 182