2012-05-10 61 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> 

我想分配txDAYS7變量。我怎麼做?

感謝

+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); 
    } 

} 

如果您運行這個,你可能希望將ReadXMLFileDefaultHandler延長一些過程的一部分,修改後的代碼。