首先是xml文档:
<types> <type id = "1"> <name>name1</name> </type> <type id = "2"> <name>name2</name> </type> <type id = "3"> <name>name3</name> </type> <type id = "4"> <name>name4</name> </type> <type id = "5"> <name>name5</name> </type> </types>
然后是解析的方法:
package com.example.spinnertest; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import android.content.Context; import android.util.Log; public class XMLManager { class Type{ String id; String name; public Type(){ } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { // TODO Auto-generated method stub return name; } } public List<Type> start(Context context){ Document doc = getDocumentFromXML(context,"types.xml"); List<Type> result = null; if(doc!=null){ result = new ArrayList<XMLManager.Type>(); Element element = doc.getDocumentElement(); NodeList entry = element.getElementsByTagName("type"); Type typeItem = null; for(int i=0;i<entry.getLength();i++){ typeItem = new Type(); Element childElement = (Element) entry.item(i); typeItem.setId(childElement.getAttribute("id")); NodeList childNodes = childElement.getChildNodes(); for(int j=0;j<childNodes.getLength();j++){ Node node = childNodes.item(j); if(node.getNodeType()==Node.ELEMENT_NODE){ if("name".equals(node.getNodeName())){ typeItem.setName(node.getTextContent()); } } } result.add(typeItem); } } return result; } public static Document getDocumentFromXML(Context context,String xmlName){ try { InputStream input = context.getResources().getAssets().open(xmlName);; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; builder = factory.newDocumentBuilder(); return builder.parse(input); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }