我真的很困惑如何解析xml到android中的列表。我使用NodeList
和getElementsByTagName
来获取组件<segment>
。当我运行和调试时,错误发生在行NodeList nL = doc.getElementsByTagNameNS(KEY_SEGMENT, "segment_id");
中。有关详细信息,请参阅我在android中的java代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listsegment_main);
ArrayList<HashMap<String, String>> menuItems = new
ArrayList<HashMap<String, String>>();
String xml = XMLParser.getXmlFromUrl();
Document doc = XMLParser.getDomElement(xml);
NodeList nL = doc.getElementsByTagNameNS(KEY_SEGMENT, "segment_id");
for (int i = 0; i < nL.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nL.item(i);
map.put(KEY_SEGMENT_ID, XMLParser.getValue(e, KEY_SEGMENT_ID));
map.put(KEY_MAIN_SEGMENT, XMLParser.getValue(e, KEY_MAIN_SEGMENT));
menuItems.add(map);
}
我的xml文件:
<map>
<segment segment_id="1050">
<segment_id>1050</segment_id>
<route_id>103</route_id>
<canvasser_id>13</canvasser_id>
<order>1</order>
....
</segment>
请帮助我。你的建议,参考资料,链接和所有论据迫切需要并对我有用。谢谢。
答案 0 :(得分:1)
我正在使用DOM解析器。请尝试下面的代码
public class XMLParsingDOMExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
Node node = nodeList.item(0);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.i("Name", ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
Log.i("Website",((Node) websiteList.item(0)).getNodeValue());
Log.i("Website Category", websiteElement.getAttribute("category"));
}
catch(Exception e) {
e.printStackTrace();
}
}
}