1

下面的程序我没看懂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);

如果有人可以详细解释,请帮助我。

4

2 回答 2

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

在这里,您实际上打开了一个到Web 服务的HTTP连接,该连接通常以. 其余的代码只是试图解析这个 XML 响应数据。XML

doc = db.parse(in);

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

因为,节点通常重复以表示数据列表,您通常将它们检索为NodeList.

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

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

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

于 2013-06-29T18:29:56.257 回答
0

首先,看看你实际分析的是什么。您调用 Web 服务来定义一个词,并返回该词的所有可用定义。如果您查看服务的返回,它是 XML 格式的吗?在 XML 中,项目是用开始和结束标记定义的。这显示在下面的片段中,它来自使用定义为牛的单词调用该 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 中的数据构建一个节点列表。

于 2013-06-29T18:33:42.327 回答