本文实例为大家分享了Android读取XML文件中数据的具体代码,供大家参考,具体内容如下
读取XML中存储的数据。将xmlfile.xml存放在assets文件夹中。在activity_main.xml中创建一个textview,用来显示读取到的数据。
XML文件内容如下:xmlfile.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<? xml version = "1.0" encoding = "UTF-8" ?> < Languages cat = "it" > < lan id = "1" > < name >Java</ name > < ide >Eclipse</ ide > < type >面向对象</ type > </ lan > < lan id = "2" > < name >C</ name > < ide >VS</ ide > < type >面向过程</ type > </ lan > < lan id = "3" > < name >C#</ name > < ide >vs</ ide > < type >面向对象</ type > </ lan > </ Languages > |
MainActivity.java
使用的是W3C的包。
用builderfactory来创建builder。并用builder打开assets的xml文件,创建出document。
读出document的element。从element中获取nodelist,再得到单个的node。注意要从item中取出字符内容。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
import java.io.IOException; 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.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView) findViewById(R.id.text); try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(getAssets().open( "xmlfile.xml" )); Element element = document.getDocumentElement(); NodeList nodeList = element.getElementsByTagName( "lan" ); text.append( "\n" ); for ( int i = 0 ; i < nodeList.getLength(); i++) { Element lan = (Element) nodeList.item(i); text.append(lan.getAttribute( "id" ) + "\n" ); text.append(lan.getElementsByTagName( "name" ).item( 0 ).getTextContent() + " " ); text.append(lan.getElementsByTagName( "ide" ).item( 0 ).getTextContent() + " " ); text.append(lan.getElementsByTagName( "type" ).item( 0 ).getTextContent() + " " ); text.append( "\n" ); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/liufish992/article/details/45419213