读取XML中存储的数据。将xmlfile.xml存放在assets文件夹中。在activity_main.xml中创建一个textview,用来显示读取到的数据。
XML文件内容如下:xmlfile.xml
<?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中取出字符内容。
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(); } } }