本文介绍了在 Android 中使用 DOM 解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 DOM 解析器从如下所示的 XML 文件中检索信息:

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.

xml 文件来自天气预报站点:http://www.meteo.si/uploads/probase/www/fproduct/text/sl/fcast_SLOVENIA_MIDDLE_latest.xml
我只需要以下行:<nn_shortText>oblačno</nn_shortText>

The xml file is from a weather forcast site:http://www.meteo.si/uploads/probase/www/fproduct/text/sl/fcast_SLOVENIA_MIDDLE_latest.xml
and I need just the following line: <nn_shortText>oblačno</nn_shortText>

推荐答案

请注意您的 XML 文件格式是否正确,

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

第一步:创建一个方法解析_Information_Value,以便解析Information标签的数据

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) {         }

    }

这篇关于在 Android 中使用 DOM 解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:23