0

我真的很困惑如何将 xml 解析到我的 android 列表中。我用NodeListwithgetElementsByTagName来获取组件<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>

请帮助我。您的建议、参考、链接和所有论点都迫切需要和对我有用。非常感谢。

4

1 回答 1

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();

    }
}

}

您也可以在此博客上找到 SAXParser

于 2012-04-18T02:50:41.167 回答