1

I'm trying to parse the sunrise and sunset time from this webservice and display them into two separate textviews.

I've been trying to follow this tutorial but I'm struggling to understand how to adapt it: http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

In that example the xml file has parent and child nodes and loops to collect them all, in my example I just want to grab two specific parameters and be able to display them.

This is the code I currently have, at the moment it calls the webservice and display the full xml file in an EditText. I need to work out how parse the individual values rather than all of it.

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

I've been attempting to sort this for a while now and I'm about ready to give up, if anybody could help me out and show me some working code to grab the sunset and sunrise times that would be amazing.

Thanks for looking x

4

4 回答 4

0

编辑:请参阅此相关问题。从 Web 服务解析日出和日落值

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

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();
        }
于 2013-03-29T21:15:28.027 回答
0

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

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

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


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

NodeList nodeList = doc.getElementsByTagName("Morning");
Node node = nodeList.get("sunrise");
String sunrise = node.getValue();
于 2013-03-29T20:06:56.140 回答
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();
     }


    }
  }

输出日出和日落。相应地修改上述内容以获取其他标签值。

于 2013-03-29T20:07:24.350 回答
0

虽然它不是解析 XML 代码的“最简单”或“最快”的实现,但我一直更喜欢使用 Android 中的 SAXParser 实用程序。

tutsplus.com提供了一个很好的教程,可以逐步分解所有内容

于 2013-03-29T20:16:50.383 回答