开发者

Using DOM parser in Android

I'm using the DOM parser to retrive information from a XML file that looks like this:

<data>
    <metData>
        <wantedInformation>
    </metData>
    <metData>
        <Information>
    </metData>
    <metData>
        <Information>
    </metData>
<data>

The problem is because I don't know how to parse only the first part of <metData>. I don't need the second and the third part, but the parser displays them anyway.

The xml file is from a weather forcast site: http://www.meteo.si/uploads/probase/www/fproduct/text/sl/开发者_StackOverflowfcast_SLOVENIA_MIDDLE_latest.xml

and I need just the following line: <nn_shortText>oblačno</nn_shortText>


Pls take care whether your XML file is well formed or not,

You have to the notice three methods which i had shown below, they are

    1. getElementsByTagName - Mention the tag which you want to parse
    2.getChildNodes - retervies the child node 
    3.getNodeValue()- with the help of this method you can access the
 value of particular tag

Step 1: Create a Method to parse _Information_Value ,inorder to parse the data of Information tag

String[] infoId=null;

public  void  parse_Information_Value() throws UnknownHostException{


        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {

            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(this.getInputStream());
            org.w3c.dom.Element root = dom.getDocumentElement();
            NodeList items = root.getElementsByTagName("metData");
            int a=items.getLength();
            int k=0;

            for (int i = 0; i < items.getLength(); i++) {
                Message_category message = new Message_category();
                Node item = items.item(i);
                NodeList properties = item.getChildNodes();
                for (int j = 0; j < properties.getLength(); j++) {
                    Node property = properties.item(j);
                    String name = property.getNodeName();
                    if (name.equalsIgnoreCase("wantedInformation")) {
                        message.setId(property.getFirstChild()
                                .getNodeValue());
                        infoId[k]=property.getFirstChild().getNodeValue();
                        k++;
                    }
                }

            }
        } catch (Exception e) {         }

    }


Depending on the size of your document, you may also want to use at a streaming oriented parser like SAX or Stax, which does not pull the whole document into memory and thus needs less memory than DOM.

Good thing is that SAX is already built into Android, so you can use it right away. See this link for a usage example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜