Parse the XML file using java to get a list of names

I am currently developing Android applications, which means learning Java I've been playing Python for years, but now I've decided to strengthen my Android phone The application basically displays a list of video games stored locally in an XML file Now, the structure of the XML file is basically Game > game (multiple) > name (plus other things that are not important now) I'm currently trying to get a list of game names I looked through the tutorials and information, but there seems to be nothing I need I want to really understand how it works, not just that I can copy / paste a piece of available code Also, remember that the namelist must end up as an Android string array to use it This is what I have now (copy / paste from the tutorial and after a lot of editing, so it's not readable. Once it actually works, I'll fix it.) Listview is now empty At least it's better than before. It won't collapse again

public static String[] parse(String filename) {
      ArrayList<String> gamesList = new ArrayList<String>();

      try {
      File file = new File(filename);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(file);
      doc.getDocumentElement().normalize();
      NodeList nodeList = doc.getElementsByTagName("game");

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

        Node fstNode = nodeList.item(s);

        //if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

          Element name = (Element) fstNode;
               Element fstElmnt = (Element) fstNode;
          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("name");
          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
          NodeList fstNm = fstNmElmnt.getChildNodes();

          gamesList.add(fstNmElmnt.toString());
        //}

      }
      } catch (Exception e) {
        e.printStackTrace();
      }
    String[] gamesArray;
    gamesArray = (String[]) gamesList.toArray(new String[0]);
    return gamesArray;
     }

Solution

In your code, add fstnmelmnt Tostring(), which is the element corresponding to the game tag Assuming that your XML is structured < name > Joe < / name >, you need to get the value of the first child node (instead of calling tostring() for the element itself):

gamesList.add(fstNmElmnt.getFirstChild().getNodeValue());

By the way, unless you have < name > tags in other parts of the document, or elements that require < Game > to do other processing at this stage, you can use the following (simpler) code:

NodeList nodeList = doc.getElementsByTagName("name");
for (int s = 0; s < nodeList.getLength(); ++s) {
    gamesList.add(nodeList.item(s).getFirstChild().getNodeValue());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>