**************************************************解析的文件放在*assets中************************************************************
*******************************************************MainActivity.class******************************************
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView1); try { //获取一个DocumentBuilder工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //通过DocumentBuilder工厂得到一个DocumentBuilder对象 DocumentBuilder builder = factory.newDocumentBuilder(); //getAssets方法获取资源文件,使用DocumentBuilder对象将资源文件流转换成Document对象 Document document = builder.parse(getAssets().open("data.xml")); //使用document对象的getdocumentElement方法获取document第一层Element对象 Element element = document.getDocumentElement(); //通过element对象中的getAttribute方法获取对象中的属性 String category = element.getAttribute("cateurl"); textView.append(category + "\n"); //通过element对象的getelementsByTagName获取该element子节点的nodeList NodeList list = element.getElementsByTagName("cate"); //遍历nodeList for (int i = 0; i < list.getLength(); i++) { //获取子节点列表中的每一个element对象 Element element1 = (Element) list.item(i); //获取到子节点对象中的id属性 String id = element1.getAttribute("id"); //获取子节点对象中的name元素 String cateurl = element1.getElementsByTagName("cateurl").item(0).getTextContent(); //获取子节点对象中的IDE元素 String catetitle = element1.getElementsByTagName("catetitle").item(0).getTextContent(); String catecontent = element1.getElementsByTagName("catecontent").item(0).getTextContent(); String cateprice = element1.getElementsByTagName("cateprice").item(0).getTextContent(); textView.append("id:" + id + "\n"); textView.append("cateurl:" + cateurl + "\n"); textView.append("catetitle:" + catetitle + "\n"); textView.append("catecontent:" + catecontent + "\n"); textView.append("cateprice:" + cateprice + "\n"); } } catch (Exception e) { // TODO: handle exception } } }