如何使用开始和结束标记内的数据访问xml解析中的标记中的数据?

时间:2014-04-25 09:58:19

标签: android xml xml-parsing domparser

我正在寻找答案,我可以从以下格式给出的标签中获取xml文件中的数据解决方案: -

<Main>
   <Item>
      <id>1</id>
      <content>Hiii this is Id 1's content.</content>
   </Item>
   <Item>
      <id>2</id>
      <content>Hiii this is Id 2's content.</content>
   </Item>
   <Item>
      <id>3</id>
      <content>Hiii this is Id 3's content.</content>
   </Item>
   <Item>
      <id>4</id>
      <content>Hiii this is Id 4's content.</content>
   </Item>
   <Item>
      <id>5</id>
      <content>Hiii this is Id 5's content.</content>
   </Item>
</Main>

我想要做的是根据我从捆绑包中获取的ID来访问数据。我使用的代码如下所示。

            try {

            InputStream is = getActivity().getAssets().open("single_item.xml");

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();


            Document doc = dBuilder.parse(is);
            doc.getDocumentElement().normalize();


            NodeList nList = doc.getElementsByTagName("item");


            for (int temp = 0; temp < nList.getLength(); temp++) {
                GetEementNode = nList.item(temp);

                if (GetEementNode.getNodeType() == Node.ELEMENT_NODE) {

                    eElement = (Element) GetEementNode;
                    String idCheck = eElement.getElementsByTagName("id").item(temp).getTextContent();

                    if(idCheck.equals(idsgot)){

                        String informationData = eElement.getElementsByTagName("content").item(temp).getTextContent();
                        information.setText(informationData);
                    }
                }
            }

        } catch (Exception e) {

        }

这里&#34; idsgot&#34;是我从捆绑中得到的id。但即使(GetEementNode.getNodeType()== Node.ELEMENT_NODE)条件,任何人都可以告诉我相同的解决方案,循环永远不会进入。再次感谢提前。

1 个答案:

答案 0 :(得分:0)

尝试使用正确的解析器,而不是编写自己的代码。 JAXB是一个非常好的选择。它需要一些设置,但一旦完成,解析xml很简单