如何在Android中解析这个XML?

时间:2010-12-14 15:11:09

标签: java android xml parsing xml-parsing

我是XML解析的新手,我有解析XML的方法。只有该方法适用于只有1个子节点的简单XML布局。

我现在必须解析一个带有子节点的子文件的XML文件(得到它:)?

这是我现在的解析方法:

protected Map<String, Maatschappij> getAutopechTel() {
    Map<String, Maatschappij> telVoorAutopech = new HashMap<String, Maatschappij>();

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder.parse(getAssets().open("autopech.xml"));
        NodeList nl = doc.getElementsByTagName("dienst");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            Maatschappij maat = new Maatschappij();

            maat.setNaam(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
            maat.setTel(Xml.innerHtml(Xml.getChildByTagName(node, "tel")));

            telVoorAutopech.put(maat.getTel(), maat);
        }
    } catch (Exception e) {
    }
    return telVoorAutopech;
}

如何调整此值以解析此类型的XML文件:

   <Message>  

    <Service>Serviceeee</Service>

      <Owner>Bla</Owner>

      <LocationFeedTo>Too</LocationFeedTo>

      <Location>http://maps.google.com/?q=52.390001,4.890145</Location>

      <Child1>

        <Child1_1>

          <Child1_1_1>ANWB</Child1_1_1>

        </Child1_1>
      </Child1>
<Message>

1 个答案:

答案 0 :(得分:0)

您可以使用SAXParser解析Android中的XML:

Here is a detailed tutorial with examplealso another one here by IBM developerWorks

  

DOM Parser很慢并且消耗很多   内存,如果它加载XML文档   其中包含大量数据。请   将SAX解析器视为解决方案   它,SAX比DOM更快并且使用   记忆力减少。

试试这个,但我还没有测试过这段代码。它以递归方式遍历所有节点,并将ELEMENT_NODE添加到Vector<Node>

public void traverseNodes(Node node, Vector<Node> nodeList)
{
    if(node.getNodeType() == Node.ELEMENT_NODE)
    {
        nodeList.add(node);
        if(node.getChildNodes().getLength() >= 1)
        {
            NodeList childNodeList = node.getChildNodes();
            for(int nodeIndex = 1;nodeIndex < childNodeList.getLength(); nodeIndex++)
            {
                traverseNodes(childNodeList.item(nodeIndex),nodeList);
            }
        }
    }

}
相关问题