不明白包含NodeList的程序的流程

时间:2013-06-29 18:19:40

标签: java android

在下面的程序中,我不了解NodeList的流程和使用。为什么在这里使用NodeList以及它在程序中使用的目的是什么?如果它很重要,请帮助我从NodeList的行中了解它。

package net.learn2develop.Networking;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element; 
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MainActivity extends Activity {
    ImageView img;    

    private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {       
        protected Bitmap doInBackground(String... url) {            
             //---download an image---
            Bitmap bitmap = DownloadImage(url[0]);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return bitmap;
        }       

        protected void onPostExecute(Bitmap bitmap) {         
            ImageView img = (ImageView) findViewById(R.id.img);
            img.setImageBitmap(bitmap);         
        }
    }

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString); 
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))                     
            throw new IOException("Not an HTTP connection");        
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
            }                     
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");            
        }
        return in;     
    }   

    private Bitmap DownloadImage(String URL)
    {        
        Bitmap bitmap = null;
        InputStream in = null;        
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            Toast.makeText(this, e1.getLocalizedMessage(), 
                    Toast.LENGTH_LONG).show();
            e1.printStackTrace();
        }
        return bitmap;                
    }

    private String DownloadText(String URL)
    {
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }

        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];          
        try {
            while ((charRead = isr.read(inputBuffer))>0)
            {                    
                //---convert the chars to a String---
                String readString = 
                    String.copyValueOf(inputBuffer, 0, charRead);                    
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }    
        return str;        
    }

    private void WordDefinition(String word) {
        InputStream in = null;
        try {
            in = OpenHttpConnection("http://services.aonaware.com/DictService/DictService.asmx/Define?word=" + word);
            Document doc = null;
            DocumentBuilderFactory dbf = 
                DocumentBuilderFactory.newInstance();
            DocumentBuilder db;            
            try {
                db = dbf.newDocumentBuilder();
                doc = db.parse(in);
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }            
            doc.getDocumentElement().normalize(); 

            //---retrieve all the <Definition> nodes---
            NodeList definitionElements = 
                doc.getElementsByTagName("Definition"); 

            String strDefinition = "";
            for (int i = 0; i < definitionElements.getLength(); i++) { 
                Node itemNode = definitionElements.item(i); 
                if (itemNode.getNodeType() == Node.ELEMENT_NODE) 
                {            
                    //---convert the Node into an Element---
                    Element definitionElement = (Element) itemNode;

                    //---get all the <WordDefinition> elements under 
                    // the <Definition> element---
                    NodeList wordDefinitionElements = 
                        (definitionElement).getElementsByTagName(
                        "WordDefinition");

                    strDefinition = "";
                    for (int j = 0; j < wordDefinitionElements.getLength(); j++) {                    
                        //---convert a <WordDefinition> Node into an Element---
                        Element wordDefinitionElement = 
                            (Element) wordDefinitionElements.item(j);

                        //---get all the child nodes under the 
                        // <WordDefinition> element---
                        NodeList textNodes = 
                            ((Node) wordDefinitionElement).getChildNodes();

                        //---get the first node, which contains the text---
                        strDefinition += 
                            ((Node) textNodes.item(0)).getNodeValue() + ". ";    
                    }                    
                    //---display the title---
                    Toast.makeText(getBaseContext(),strDefinition, 
                        Toast.LENGTH_SHORT).show();
                } 
            }            
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();            
        }        
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

如果有人能详细解释,请帮助我们。

2 个答案:

答案 0 :(得分:1)

OpenHttpConnection(
"http://services.aonaware.com/DictService/DictService.asmx/Define?word=" + word);

在这里,您实际上打开了一个 HTTP 连接到 Web服务,它通常以XML中编码的服务输出进行响应。其余的代码只是尝试解析这个XML响应数据。

doc = db.parse(in);

在这里,您使用Document将服务输出解析为DOM DocumentBuilder对象。文档对象用于遍历XML中存在的不同节点(您可以将它们视为<xmlTags>)。

因为,节点通常会重复以表示您通常将其作为NodeList检索的数据列表。

//---retrieve all the <Definition> nodes---
NodeList definitionElements = 
    doc.getElementsByTagName("Definition");

在这里,您只是检索XML响应中编码为<Definition>个节点的所有单词定义。 NodeList#getLength()为您提供了以后用于循环和处理它们的定义数。 NodeList#item(i)只是将指定索引处的定义作为Node对象返回。

同样,其余的处理只反映了您尝试解析的文档结构。它会因服务而异,或者只要服务更改其输出XML格式,您就需要更新它。查看org.w3c.dom的JavaDocs,了解代码用于解析此XML的所有不同类。

答案 1 :(得分:0)

首先,看看你实际在分析什么。您调用Web服务来定义单词,并返回该单词可用的所有定义。如果您查看服务的返回,是否为XML格式。在XML中,项目使用开始和结束标记定义。这显示在下面的代码段中,该代码片段来自于使用定义为cow的单词调用该Web服务。

<Definition>
    <Word>cow</Word>
    <Dictionary>
        <Id>easton</Id>
        <Name>Easton's 1897 Bible Dictionary</Name>
    </Dictionary>
    <WordDefinition>
        Cow A cow and her calf were not to be killed on the same day (Lev. 22:28; Ex. 23:19; Deut. 22:6, 7). The reason for this enactment is not given. A state of great poverty is described in the words of Isa. 7:21-25, where, instead of possessing great resources, a man shall depend for the subsistence of himself and his family on what a single cow and two sheep could yield.
    </WordDefinition>
</Definition>

<Definition>是开始标记,</Definition>是结束标记。您可以将开始和结束标记之间的任何内容视为节点。在这种情况下,代码将根据此XML中的数据构建节点列表。