简体   繁体   中英

Didn't understand the flow of the program containing a NodeList

In the program below I did not understand the flow and the use of NodeList. Why is the NodeList used here and for what purpose it is used in the program? If it's important please help me to understand it from the line NodeList came in existence.

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

Please help me guys if anyone can explain it in detail.

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

Here you're actually opening an HTTP connection to a web service which usually responds with service output encoded in XML . The rest of the code is nothing but trying to parse this XML response data.

doc = db.parse(in);

Here, you've parsed the service output into a DOM Document object using a DocumentBuilder . A document object is used to traverse through the different nodes (you can think of them as <xmlTags> ) present in the XML.

Since, the nodes usually repeat to represent a list of data you typically retrieve them as a NodeList .

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

Here, you're just retrieving all the word definitions encoded as <Definition> nodes within the XML response. NodeList#getLength() gives you the number of definitions found that you later use to loop over and process them. NodeList#item(i) simply returns the definition present at the specified index as a Node object.

Similarly, the rest of the processing just reflects the document structure you're trying to parse. It would differ from service to service or you would need to update it whenever the service changes it's output XML format. Take a look at JavaDocs for org.w3c.dom to understand all the different classes your code has employed to parse this XML.

First, a look at what you are actually analyzing. Your calling a web service to define a word, and returning all the definitions available for that word. If you have a look at the return from the service, is it in XML. In XML, items are defined with a start and an end tag. This is shown in the snippet below, which came from calling that web service with a word defined as cow.

<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>

Where <Definition> is the start tag and </Definition> is the end tag. You can treat anything that is between a start and end tag as a node. In this case, the code is going to build a list of nodes from data within this XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM