简体   繁体   English

如何在Android中解析此XML?

[英]How to parse this XML in Android?

I am quite new to XML parsing and I have my method of parsing XML. 我对XML解析非常陌生,并且有解析XML的方法。 Only that method is for simple XML layouts with just 1 child node. 只有该方法适用于只有1个子节点的简单XML布局。

I now have to parse an XML file with childs that have childs that have childs (got it :)?) 我现在必须解析一个XML文件,该XML文件中的childs包含childs(get :)?

This is the parse-method I have now: 这是我现在拥有的解析方法:

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;
}

How must I adjust this in order to parse this type of XML file: 为了解析这种类型的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>

You can use SAXParser to parse XML in Android : 您可以使用SAXParser在Android中解析XML:

Here is a detailed tutorial with example and also another one here by IBM developerWorks . 这是带示例的详细教程, IBM developerWorks的另一个 示例

DOM Parser is slow and consume a lot memory if it load a XML document which contains a lot of data. 如果DOM Parser加载包含大量数据的XML文档,则速度很慢并且会占用大量内存。 Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory. 请考虑使用SAX解析器作为解决方案,SAX比DOM更快,并且使用更少的内存。

Try this one out but I haven't tested this code yet. 试试这个,但是我还没有测试这段代码。 It recursively traverses all the nodes and adds which are ELEMENT_NODE to the Vector<Node> . 它递归地遍历所有节点,并将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);
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM