简体   繁体   中英

Parse XML using DOM in android

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

my xml is looking like this

在此处输入图片说明

below is my 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

of Companies list

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

when i select Company ABC

only two provision list should display

       Alberta
       Ontario

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

Use Node.getChildNodes() over the "company" nodes. Then, to get the child province nodes, compare by name. Example:

    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++) {
        Node companyNode = n1.item(i);
        NodeList childNodes = companyNode.getChildNodes();
        // Here we're getting child nodes inside the company node.
        // Only direct childs will be returned (name and province)  

        for (int j = 0; j < childNodes.getLength(); j++) {
            Node childNode = childNodes.item(j);
            if("province".equalsIgnoreCase(childNode.getName())){
                //Do something with province
            }
        }
    }

This should do it:

        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"));
                 }
            }
        }

Try the following code:

public class MainActivity  extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /** Create a new layout to display the view */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(1);

    /** Create a new textview array to display the results */
    TextView name[];
    TextView website[];
    TextView category[];

    try {

        URL url = new URL(
                "http://xyz.com/aa.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();

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

        /** Assign textview array lenght by arraylist size */
        name = new TextView[nodeList.getLength()];
        website = new TextView[nodeList.getLength()];
        category = new TextView[nodeList.getLength()];

        for (int i = 0; i < nodeList.getLength(); i++) {

            Node node = nodeList.item(i);

            name[i] = new TextView(this);
            website[i] = new TextView(this);
            category[i] = new TextView(this);

            Element fstElmnt = (Element) node;
            NodeList nameList = fstElmnt.getElementsByTagName("name");
            Element nameElement = (Element) nameList.item(0);
            nameList = nameElement.getChildNodes();
            name[i].setText("Name = "
                    + ((Node) nameList.item(0)).getNodeValue());

            NodeList websiteList = fstElmnt.getElementsByTagName("website");
            Element websiteElement = (Element) websiteList.item(0);
            websiteList = websiteElement.getChildNodes();
            website[i].setText("Website = "
                    + ((Node) websiteList.item(0)).getNodeValue());

            category[i].setText("Website Category = "
                    + websiteElement.getAttribute("category"));

            layout.addView(name[i]);
            layout.addView(website[i]);
            layout.addView(category[i]);

        }
    } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
    }

    /** Set the layout view to display */
    setContentView(layout);

}
}

The getElementsBytagName called on the document object will always return the list of all the nodes with the given tag name in the whole document. Instead, filter out the single company element you are interested in, and then call getElementsByTagName on it . Eg

Element companyEl = doc.getElementById(desiredCompanyId);
if (companyEl != null) { // always good to check
    NodeList n1 = companyEl.getElementsByTagName("province");

    // your code here
}

Try with this code

for (int i = 0; i < nodeList.getLength(); i++) {

        Node node = nodeList.item(i);

        name[i] = new TextView(this);
        website[i] = new TextView(this);
        category[i] = new TextView(this);

        Element fstElmnt = (Element) node;
        NodeList nameList = fstElmnt.getElementsByTagName("name");
        Element nameElement = (Element) nameList.item(0);
        nameList = nameElement.getChildNodes();
        name[i].setText("Name = "
                + ((Node) nameList.item(0)).getNodeValue());

        NodeList websiteList = fstElmnt.getElementsByTagName("website");
        Element websiteElement = (Element) websiteList.item(0);
        websiteList = websiteElement.getChildNodes();
        website[i].setText("Website = "
                + ((Node) websiteList.item(0)).getNodeValue());

        category[i].setText("Website Category = "
                + websiteElement.getAttribute("category"));

        layout.addView(name[i]);
        layout.addView(website[i]);
        layout.addView(category[i]);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM