从WebService解析xml文件的各个部分 - Android

时间:2013-03-29 20:02:18

标签: java android web-services

我正在尝试从此webservice解析日出和日落时间,并将它们显示为两个单独的文本视图。

我一直在努力学习本教程,但我很难理解如何适应它: http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

在该示例中,xml文件具有父节点和子节点以及用于收集它们的循环,在我的示例中,我只想获取两个特定参数并能够显示它们。

这是我目前拥有的代码,目前它调用webservice并在EditText中显示完整的xml文件。我需要弄清楚如何解析单个值而不是全部值。

      package com.authorwjf.http_get;
      import java.io.IOException;
      import java.io.InputStream;
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.protocol.BasicHttpContext;
      import org.apache.http.protocol.HttpContext;
      import android.app.Activity;
      import android.os.AsyncTask;
      import android.os.Bundle;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.EditText;

public class Main extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    findViewById(R.id.my_button).setOnClickListener(this);
}

@Override
public void onClick(View arg0) {
    Button b = (Button)findViewById(R.id.my_button);
    b.setClickable(false);
    new LongRunningGetIO().execute();
}

private class LongRunningGetIO extends AsyncTask <Void, Void, String> {

    protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
       InputStream in = entity.getContent();
         StringBuffer out = new StringBuffer();
         int n = 1;
         while (n>0) {
             byte[] b = new byte[4096];
             n =  in.read(b);
             if (n>0) out.append(new String(b, 0, n));
         }
         return out.toString();
    }

    @Override
    protected String doInBackground(Void... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        String finalURL = "http://www.earthtools.org/sun/52.77431872/-1.20639/4/12/99/0";
        HttpGet httpGet = new HttpGet(finalURL);
        String text = null;
        try {
            HttpResponse response = httpClient.execute(httpGet,
                    localContext);
            HttpEntity entity = response.getEntity();
            text = getASCIIContentFromEntity(entity);
        } catch (Exception e) {
            return e.getLocalizedMessage();
        }
        return text;
    }   

    protected void onPostExecute(String results) {
        if (results!=null) {
            EditText et = (EditText)findViewById(R.id.my_edit);
            et.setText(results);
        }
        Button b = (Button)findViewById(R.id.my_button);
        b.setClickable(true);
    }
}
}

我一直试图对此进行一段时间的排序,我准备放弃,如果有人可以帮助我并向我展示一些工作代码来抓住令人惊叹的日落和日出时间。< / p>

感谢您寻找x

4 个答案:

答案 0 :(得分:0)

您需要使用XML DOM解析器,因为它是最简单的。

您应该使用resultsDocumentBuilderFactory文本发送到XML解析器,然后从解析器中请求各种值,例如日落和日出。

我建议您遵循本教程:Android XML Parsing Tutorial – Using DOMParser


日出示例(伪代码... 非常伪代码):

NodeList nodeList = doc.getElementsByTagName("Morning");
Node node = nodeList.get("sunrise");
String sunrise = node.getValue();

答案 1 :(得分:0)

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

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

您可以选择Sax解析器或w3c dom解析器。

上面有相同的教程。

public class MainActivity extends Activity {
String lsunrise,sunset;
String xml=    "<sun >"+
"<version>1.0</version>"+
"<location>"+
"<latitude>52.77431872</latitude>"+
"<longitude>-1.20639</longitude>"+
"</location>"+
"<date>"+
"<day>4</day>"+
"<month>12</month>"+
"<timezone>0</timezone>"+
"<dst>0</dst>"+
"</date>"+
"<morning>"+
"<sunrise>07:45:31</sunrise>"+
"<twilight>"+
"<civil>07:05:54</civil>"+
"<nautical>06:22:57</nautical>"+
"<astronomical>05:41:56</astronomical>"+
"</twilight>"+
"</morning>"+
"<evening>"+
"<sunset>16:02:28</sunset>"+
"<twilight>"+
"<civil>16:42:03</civil>"+
"<nautical>17:24:58</nautical>"+
"<astronomical>18:05:57</astronomical>"+
"</twilight>"+
"</evening>"+
"</sun>";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    parse();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
  void parse()
   { try 
        {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    DefaultHandler handler = new DefaultHandler() {


     boolean sr=false;
     boolean ss=false;


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

        //System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("sunrise")) {
            sr=true;
        }

        if (qName.equalsIgnoreCase("sunset")) {
            ss=true;
        }



    }

    public void endElement(String uri, String localName,
        String qName) throws SAXException {

        //System.out.println("End Element :" + qName);

    }

    public void characters(char ch[], int start, int length) throws SAXException         
        {
        if (sr) {
            System.out.println("FSun rise: " + new String(ch, start, length));
            sr = false;
        }

        if (ss) {
            System.out.println("Sun set : " + new String(ch, start, length));
            ss = false;
        }


    }

     };

       saxParser.parse(is, handler);

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


    }
  }

输出snrise和sunset。相应地修改上面的内容以获取其他标记值。

答案 2 :(得分:0)

虽然它不是解析XML代码的“最简单”或“最快”的实现,但我总是倾向于使用Android的SAXParser实用程序。

一个很好的教程可以逐步打破所有内容is from tutsplus.com

答案 3 :(得分:0)

编辑:请参阅此相关问题。 Parsing sunrise and sunset values from web service

您可以解析xml并将值设置为视图。 看看这个tutorial

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

//here's your xml string.
String test = "<sun xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.earthtools.org/sun.xsd\"><version>1.0</version><location><latitude>52.77431872</latitude><longitude>-1.20639</longitude></location><date><day>4</day><month>12</month><timezone>0</timezone><dst>0</dst></date><morning><sunrise>07:45:31</sunrise><twilight><civil>07:05:54</civil><nautical>06:22:57</nautical><astronomical>05:41:56</astronomical></twilight></morning><evening><sunset>16:02:28</sunset><twilight><civil>16:42:03</civil><nautical>17:24:58</nautical><astronomical>18:05:57</astronomical></twilight></evening></sun>";
try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource s = new InputSource(new StringReader(test)); 
        Document doc = dBuilder.parse(s);

        doc.getDocumentElement().normalize();

        Log.v("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("morning");

        Log.v("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("sunrise : " + eElement.getElementsByTagName("sunrise").item(0).getTextContent());

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