2012-05-10 6 views
0

http 요청에 대해 xml repsonse가 표시됩니다. 나는XML 응답 변수에 값을 할당하는 방법

String str = in.readLine(); 

변수 문자열로 저장하고 str의 내용은 다음과 같습니다

<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> 

나는 변수 tx, DAYS7을 할당 할. 어떻게해야합니까? 당신은 당신이 DefaultHandler에서 ReadXMLFile을 확장 할 수있는 몇 가지 과정의 일부로서이를 실행하는 경우

감사

+0

사용중인 프로그래밍 언어를 알려 주시면 도움이 될 것입니다. – Filburt

+0

안녕하세요 죄송합니다 Java를 사용하고 있습니다 – SUM

+2

http://stackoverflow.com/questions/5947450/how-to-parse-this-xml-using-java –

답변

0

는 약간 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); 
    } 

} 

에서 코드를 수정했습니다.

관련 문제