在Android中使用DOM解析XMLAndroid、DOM、XML

2023-09-13 02:22:29 作者:潇洒亼◇生

我想根据选择的用户解析XML和显示列表

Hi i want to parse XML and display list based on selection of user

我的XML是这样看

下面是我的code

      try {
            XMLParser parser = new XMLParser();
            Document doc = parser.getDomElement(xml); // getting DOM element
            NodeList n1 = doc.getElementsByTagName("company");

            // looping through all item nodes <item>
            for (int i = 0; i < n1.getLength(); i++) {
                // creating new HashMap
                Element e = (Element) n1.item(i);

                System.out.println("name node "+parser.getValue(e, "name"));
            }

通过这样的方式,我越来越喜欢

by this way i am getting the output like

  Company ABC
  Company XYZ

的企业名单

但       我会写code像

but i would write code like

        NodeList n1 = doc.getElementsByTagName("province"); 
        // looping through all item nodes <item>
            for (int i = 0; i < n1.getLength(); i++) {
                // creating new HashMap
                Element e = (Element) n1.item(i);

                System.out.println("name node "+parser.getValue(e, "name"));
            }

我收到省名单

i am getting list of province name

   Alberta
   Ontario
   New York
   Florida

但它应该像这样

but it should work like this

当我选择ABC公司

只有两个条款清单应显示

only two provision list should display

       Alberta
       Ontario

不应该所有显示任何机构可以帮助我如何重写我的code

not should all display can any body help me how to rewrite my code

推荐答案

这应该做到这一点:

        XMLParser parser = new XMLParser();
        Document doc = parser.getDomElement(xml); // getting DOM element
        NodeList n1 = doc.getElementsByTagName("company");

        // looping through all item nodes <item>
        for (int i = 0; i < n1.getLength(); i++) {
            Element e = (Element) n1.item(i);
            System.out.println("name node "  +parser.getValue(e, "name"));
            NodeList children = e.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                 Node child = children.item(j);
                 if (child.getNodeName().equalsIgnoreCase("province")) {
                      System.out.println("name node " + parser.getValue((Element)child, "name"));
                 }
            }
        }
 
精彩推荐
图片推荐