2012-03-21 3 views
0

1つのタグだけを表示するために、RESTベースのサービスにアクセスして返されたXMLデータを解析する必要があります。たとえば、以下のXMLデータを解析して、firstnameタグとvalue Johnのみを表示します。RESTClientがXMLデータを返した後のSaxParserコードとのインターフェイス方法

XMLデータがRESTClientによって返されると、SAX解析コードとのインターフェース方法を理解するのは難しいです。私は、さまざまなサンプルコードから学んだ後、異なるアプローチを試みましたが、同じ正確な目的を持っていないため、部分的にはそれを理解できません。ですから、データを解析コードに呼び出す/渡す方法と、解析コードが別のクラスにあるかどうかなど、解析コードから返す方法を教えてください。私はいくつかの指針なしでは基本的に無知です。関連するRESTClientコードを以下に示します。ありがとう!

public class RESTClient { 

public static String callRESTService(String url) { 

    String result = null; 
    HttpClient httpclient = new DefaultHttpClient(); 

    // Prepare a request object 
    HttpGet httpget = new HttpGet(url); 

    // Execute the request 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httpget); 

     // Get hold of the response entity 
     HttpEntity entity = response.getEntity(); 
     // If the response does not enclose an entity, there is no need 
     // to worry about connection release 

     if (entity != null) { 

      InputStream instream = entity.getContent(); 

      SAXParserFactory spf = SAXParserFactory.newInstance(); 
          SAXParser sp; 

      try (

       sp = spf.newSAXParser(); 
       XMLReader xr = sp.getXMLReader(); 


       DefaultHandler handler = new DefaultHandler(); 
       xr.setContentHandler(handler); 

       InputSource is = new InputSource(instream); 
       xr.parse(is); 

       //what should/can be returned here from the parsing code: 
       //String, InputSource, InputStream?. Convert data type? 


      } 


      catch (SAXException e) 
      { 

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

       e.printStackTrace(); 
      } 
     } 


    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return result; 
    } 
) 
+0

あなた自身の 'DefaultHandler'を実装する必要があります – zapl

答えて

1


私はあなたが別のファイルにあなたのパーサーコードを維持すべきであると主張しています。 RestClientは遠隔地からのデータの送受信のみを担当するためです。これはまた、2つの構成要素間の結合を失うことももたらす。
解析コードの出力は、必要に応じて異なります。 (個人的に私はHashMapのリストを返しています)

+0

アドバイスありがとうございます! – macrogeo

0

ここではPOJOを返すことをお勧めします。

関連する問題