1. 程式人生 > >Android解析xml檔案獲取資料練習

Android解析xml檔案獲取資料練習

前幾天單詞app中,已經可以顯示單詞了,對比有道詞典的單詞表,主要是有單詞備註的功能,可以進行聯想記憶,而且程式佔用空間小,沒有太多的通知資訊。

以前使用有道詞典的單詞儲存了一些單詞,有道里的單詞可以匯出到xml檔案中

格式如下

<wordbook><item>    <word>unveil</word>
    <trans><![CDATA[vt. 使公諸於眾,揭開;揭幕 
vi. 除去面紗;顯露 
unveil: 揭露 | 使公諸於眾 | 揭開]]></trans>
    <phonetic><![CDATA[[ʌn'veɪl]]]></phonetic>
    <tags></tags>
    <progress>2</progress>
</item><item>    <word>prominence</word>
    <trans><![CDATA[n. 突出;顯著;突出物;卓越 
Prominence: 日珥 | 突出 | 顯著]]></trans>
    <phonetic><![CDATA[['prɒmɪnəns]]]></phonetic>
    <tags></tags>
    <progress>1</progress>
</item></wordbook>

考慮增加匯入功能,讀取單詞xml獲取資料儲存進去

在java上進行xml解析練習

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Test {

	public static void getDataFromXml(String fileName)  
    {  
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        try  
        {  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            Document doc = db.parse(fileName);  
  
            NodeList wordList = doc.getElementsByTagName("item");  
            System.out.println("共有" + wordList.getLength() + "個word節點");  
            for (int i = 0; i < wordList.getLength(); i++)  
            {  
            	if (i == 3)
            	{
            		break;
            	}
            	
            	
                Node aWord = wordList.item(i);  
                Element elem = (Element) aWord;  
              
                for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling())  
                {  
        //        	System.out.println("node.getNodeType() = " + node.getNodeType()); 
                    if (node.getNodeType() == Node.ELEMENT_NODE)  
                    {  
                        String name = node.getNodeName(); 
                        if (name.equals("word") || name.equals("trans"))
                        {
                        	String value = node.getFirstChild().getNodeValue();  
                            System.out.print(name + ":" + value + "\t"); 
                        }
                       
                    }  
                }  
                System.out.println();  
            }  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
            System.out.println(e); 
        }  
    } 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("----------");
		
		getDataFromXml("D:\\2015\\06\\words.xml");
	}

}

把解析方法移植到單詞app中,出現錯誤,MalformedURLException: Protocol not found

解決方案,路徑修改為 file:///mnt/sdcard/words.xml

即增加file://

/mnt/sdcard/words.xml  為xml檔案儲存的地方,即手機上開啟 檔案管理 所在的路徑

    //
    public void getDataFromXml(String fileName)
    {
    	Log.d("test614", fileName);
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        try  
        {  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            Document doc = db.parse(fileName);  
  
            NodeList wordList = doc.getElementsByTagName("item");  
            System.out.println("共有" + wordList.getLength() + "個word節點");
            Log.d("test614", "共有" + wordList.getLength() + "個word節點");
            for (int i = 0; i < wordList.getLength(); i++)  
            {             	
                Node aWord = wordList.item(i);  
                Element elem = (Element) aWord;  
              
                String wname = " ";
                String wtrans = " ";
                for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling())  
                {   
                    if (node.getNodeType() == Node.ELEMENT_NODE)  
                    {  
                        String name = node.getNodeName(); 
                        if (name.equals("word"))
                        {
                        	wname = node.getFirstChild().getNodeValue();                             
                        }
                        if (name.equals("trans"))
                        {
                        	wtrans = node.getFirstChild().getNodeValue();                             
                        }                      
                    }  
                }  
                if (!wname.equals(" "))  
                {
                	this.insertStuInfo(wname, wtrans, " ");
                }
            }  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
            System.out.println(e); 
            Log.d("test614", e.toString());
        } 
    }

	
呼叫
	getDataFromXml("file:///mnt/sdcard/words.xml");

//insert a record
//6-21
private void insertStuInfo(String word, String trans, String notes) 
{
ContentValues values = new ContentValues();
values.put(StuInfoColumns.WORD_NAME, word);
values.put(StuInfoColumns.WORD_MEANING, trans);
values.put(StuInfoColumns.WORD_NOTES, notes);

getContentResolver().insert(StuInfoColumns.CONTENT_URI, values);


}

這樣,就可以把xml裡的單詞寫到資料庫了

根據字母表排序的單詞對出現大寫字母優先於小寫字母的現象,可以使用upper對排序條件進行修飾

增加解析tags內容後,發現如果內容為空,會出錯

node.getFirstChild().getNodeValue()
 //will lead a nullPointer exception

解析方法的優化:
   //
    public void getDataFromXml(String fileName)
    {
    	Log.d("test614", fileName);
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        try  
        {  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            Document doc = db.parse(fileName);  
  
            NodeList wordList = doc.getElementsByTagName("item");  
            System.out.println("共有" + wordList.getLength() + "個word節點");
            Log.d("test614", "共有" + wordList.getLength() + "個word節點");
            for (int i = 0; i < wordList.getLength(); i++)  
            {             	
                Node aWord = wordList.item(i);  
                Element elem = (Element) aWord;  
              
                String wname = " ";
                String wtrans = " ";
                String wnotes = " ";
                for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling())  
                {   
                    if (node.getNodeType() == Node.ELEMENT_NODE)  
                    {  
                    	//if there is no value, continue
                    	//otherwise node.getFirstChild().getNodeValue()
                    	//will lead a nullPointer exception
                    	if (node.getFirstChild() == null)
                    	{
                    		continue;
                    	}
                    	
                        String name = node.getNodeName(); 
                        if (name.equals("word") )
                        {                       	
                        	wname = node.getFirstChild().getNodeValue();  
                        	Log.d("test614", "word=" + wname);
                        }
                        else if (name.equals("trans"))
                        {
                        	//node.getNodeValue()
                        	wtrans = node.getFirstChild().getNodeValue(); 
                        	Log.d("test614", "trans=" + wtrans);
                        }
                        else if (name.equals("tags"))
                        {
                        	wnotes = node.getFirstChild().getNodeValue();
                        	if (wnotes == null)
                        	{
                        		Log.d("test614", "tags=null");
                        	}
                        	else
                        	{
                        		Log.d("test614", "tags=" + wnotes);
                        	}
                        }
                    }  
                }  
                
                if (wname!= null && !wname.equals(" "))  
                {
                	Log.d("test614", "if (!wname.equals() " + wname);
                	this.insertStuInfo(wname, wtrans, wnotes);
                }
            }  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
            System.out.println(e); 
            Log.d("test614", e.toString());
        } 
    }