ANDROID:解析XML [英] ANDROID: Parsing XML

查看:260
本文介绍了ANDROID:解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是一个开发商,我刚涉足编程。一个领域我从来不明白的是XML解析。可悲的是,我的最新的工程我需要做的这事对于一个Android应用程序。它的原型是我做的工作。

I'm not a developer, I just dabble in programming. One area I never understand is XML parsing. Sadly, for my latest "project" I need to do this very thing for an android app. Its a prototype that I am doing for work.

我有这样的XML(一实体模型文件):

I have this XML (a mock-up file):

<feed version="201010011221" > 
  <period from="2010-10-01T10:08:34Z" to="2010-10-01T10:08:34Z"> 
    <lines> 
      <line id="SKI" name="Ski" shortname="ski" status="1 calls queued"> 
        <calls> 
          <call id="6584" created="2010-10-01T11:22:42Z">
            <booking>1275243</booking>
          </call> 
        </calls> 
      </line> 
      <line id="CRU" name="Cruise" shortname="cruise" status="0 calls queued"> 
        <calls /> 
      </line> 
      <line id="VIL" name="Villas" shortname="villas" status="2 calls queued"> 
        <calls> 
          <call id="25878" created="2010-10-01T10:22:42Z">
            <booking>1077244</booking>
          </call> 
          <call id="25878" created="2010-10-01T10:22:42Z">
            <booking>1077244</booking>
          </call> 
        </calls> 
      </line>
    </lines>
  </period> 
</feed>

我有一些code,它让我的每一个节点列表:

I have some code that gets me a NodeList of each :

inputStream = OpenHttpConnection(URL);
Document document = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder;
documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.parse(inputStream);
document.getDocumentElement().normalize();
NodeList lineNodes = document.getElementsByTagName("line");

我不知道下一步该怎么做。我的code似乎很长了。我GOOGLE了更好的方法,但一些清洁剂code,我发现,我不能去上班。

I'm not sure what to do next. My code seems quite long for this. I've googled for better methods, but some cleaner code I found, I couldn't get to work.

有什么好看的Andr​​oid XML的教程在那里?或者有人可以帮我解决这个code?

Are there any good Android XML tutorials out there? Or can someone assist me with this code?

我需要每进一个HashMap其中string是ID。

I need to get each into a HashMap where String is the ID.

行是类中显示的所有信息。

Line is class of all info shown.

谢谢 尼尔

推荐答案

我ñ宁可不使用DOM,因为它有一个更大的内存占用。随着DOM整个XML结构首次加载到内存中,然后将它正在处理中。这可能不是为移动开发的最佳解决方案。

I'd n rather not use DOM as it has a bigger memory footprint. With DOM the whole XML structure is first loaded into memory and then it is being processed. This might not be the best solution for mobile development.

使用SAX解析器附带的Andr​​oid。这是一个事件驱动的方法。每一个开始标记,在标签和它们出现时结束标记火灾事件之间的内容。实际上它可以处理更多的事件,但这些是最常用的事件。这意味着该SAX解析器由一个处理每行一个,而无需装载整个XML结构到内存第一

Use the SAX parser which comes with Android. It is an event driven approach. Every starting tag, content in between tags and end tag fire events when they occur. Actually it can handle more events but those are the most commonly used events. This means that the SAX parser processes each line one by one without loading the whole XML structure into memory first.

我会后一个例子特别是明天的问题。

I will post an example for your particular problem tomorrow.

编辑:这里是承诺的内容处理程序的例子

Here is the promised content handler example.

import java.util.HashMap;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class MyContentHandler implements ContentHandler {

    private HashMap<String, Object> feed;
    private HashMap<String, Object> peroidContent;
    private HashMap<String, Object> callContent;
    private HashMap<String, Object> callsMap;
    private HashMap<String, Object> lineContent;
    private HashMap<String, Object> linesMap;

    private String text;
    private String callId;
    private String lineId;

    @Override
    public void startDocument() throws SAXException {
        /* You can perform some action in this method
         * for example to reset some sort of Collection
         * or any other variable you want. It gets called
         * every time a document starts. */
        feed = new HashMap<String, Object>();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts) throws SAXException {
        // Gets called every time an opening tag is encountered.
        if(localName.equalsIgnoreCase("FEED")) {
            /* We've found a "feed" opening tag so we capture its
             * version attribute and put it into our HashMap.*/
            feed.put("Version", atts.getValue("version"));
        } else if(localName.equalsIgnoreCase("PEROID")) {
            peroidContent = new HashMap<String, Object>();
            peroidContent.put("From", atts.getValue("from"));
            peroidContent.put("to", atts.getValue("to"));
        } else if(localName.equalsIgnoreCase("LINE")) {
            linesMap = new HashMap<String, Object>();
        } else if(localName.equalsIgnoreCase("LINE")) {
            lineContent = new HashMap<String, Object>();
            lineId = atts.getValue("id");
            lineContent.put("name", atts.getValue("name"));
            lineContent.put("shortname", atts.getValue("shortname"));
            lineContent.put("status", atts.getValue("status"));
        } else if(localName.equalsIgnoreCase("CALLS")) {
            callsMap = new HashMap<String, Object>();
        } else if(localName.equalsIgnoreCase("CALL")) {
            callContent = new HashMap<String, Object>();
            callId = atts.getValue("Id");
            callContent.put("created", atts.getValue("created"));
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        /* Gets called every time in between an opening tag and
         * a closing tag if characters are encountered. */
        text = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // Gets called every time a closing tag is encountered.
        if(localName.equalsIgnoreCase("FEED")) {
            feed.put("Peroid", peroidContent);
        } else if(localName.equalsIgnoreCase("PEROID")) {
            peroidContent.put("Lines", linesMap);
        } else if(localName.equalsIgnoreCase("LINES")) {
            linesMap.put(lineId, lineContent);
        } else if(localName.equalsIgnoreCase("LINE")) {
            lineContent.put("Calls", callsMap);
        } else if(localName.equalsIgnoreCase("CALLS")) {
            callsMap.put(callId, callContent);
        } else if(localName.equalsIgnoreCase("BOOKING")) {
            callContent.put("Booking", text.toString());
        }
    }

    @Override
    public void endDocument() throws SAXException {
        /* You can perform some action in this method
         * for example to reset some sort of Collection
         * or any other variable you want. It gets called
         * every time a document end is reached. */
        SAXParsingFun.setHashMap(feed);
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void processingInstruction(String target, String data)
            throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void setDocumentLocator(Locator locator) {
        // TODO Auto-generated method stub
    }

    @Override
    public void skippedEntity(String name) throws SAXException {
        // TODO Auto-generated method stub
    }

    @Override
    public void startPrefixMapping(String prefix, String uri)
            throws SAXException {
        // TODO Auto-generated method stub
    }
}

有很多解释上的计算器如何解析XML文件我已经离开了这一点,只是显示你的更有趣的一部分;内容处理程序。

There are a lot of explanations on StackOverflow about how to parse a XML file I have left that out and just shown you the more interesting part; the content handler.

现在最有趣的部分是注释,所以你能理解我想要做的事情。

Now most of the interesting parts are commented so you can understand what I'm trying to do.

我已经实现了接口的ContentHandler 只是为了告诉你,还有更多的可用方法,也许你会在将来需要的其中之一。但是,可以从班的DefaultHandler ,而不是扩展和只是简单地覆盖所需的方法。所有你要做的基本上是检查某些标记的出现,然后在触发某些事件。如果你想preserve的XML文件中的元素的顺序,那么你只需使用的的LinkedHashMap 代替的HashMap

I have implemented the interface ContentHandler just to show you that there are more methods available, maybe you'll need one of them in the future. You can however extend from the class DefaultHandler instead and just overwrite the needed methods. All you do is basically check for the occurrence of certain tags and then trigger certain events upon that. If you want to preserve the order of the elements in the XML file then you simply use a LinkedHashMap instead of a HashMap.

我希望它能帮助。

这篇关于ANDROID:解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆