1. 程式人生 > >Android如何獲取asset下的xml檔案,並解析

Android如何獲取asset下的xml檔案,並解析

1.asset下的自定義xml檔案:
<Language cat="it">
    <lan id="1">
        <name>Java</name>
     	<ide>Eclipse</ide>
     </lan>
     <lan id="2">
         <name>Swift</name>
         <ide>Xcode</ide>
     </lan>
     <lan id="3">
         <name>C#</name>
         <ide>Visual Studio</ide>
     </lan>
</Language>
2.activity解析程式碼:
</pre><pre name="code" class="java">import java.io.IOException;
import java.io.InputStream;
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.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private TextView tv_show;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv_show = (TextView) findViewById(R.id.tv_show);
		
		try {
			//傳入檔名:language.xml;用來獲取流
			InputStream is = getAssets().open("language.xml");
			//首先創造:DocumentBuilderFactory物件
			DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
			//獲取:DocumentBuilder物件
			DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder();
			//將資料來源轉換成:document 物件
			Document document = dBuilder.parse(is);
			//獲取根元素
			Element element = (Element) document.getDocumentElement();
			//獲取子物件的數值 讀取lan標籤的內容
			NodeList nodeList = element.getElementsByTagName("lan");
			for (int i = 0; i < nodeList.getLength(); i++) {
				//獲取對應的物件
				Element lan = (Element) nodeList.item(i);
				//lan.getAttribute("id") 獲取id的值
				tv_show.append(lan.getAttribute("id")+"\n");
				//獲取name標籤下的內容
				tv_show.append(lan.getElementsByTagName("name").item(0).getTextContent()+"\n");
				//獲取ide標籤下的內容
				tv_show.append(lan.getElementsByTagName("ide").item(0).getTextContent()+"\n");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
}