Parsing an XML file in Java to get a list of names

I am currently working on an Android application, and that means learning Java. I played with Python for several years, but decided it was time to activate now that I have an Android phone. The application basically displays a list of video games stored locally in the XML file. Right now, the structure of the XML file is basically games> game (Multiple)> name (plus other things that are not important right now). I'm currently trying to get a list of game names. I was looking for textbooks and information, but none of this looks like what I need. I want to actually understand how this works, and not just create a piece of code that I can copy / paste. Also, keep in mind that the list of names must end up as an array of strings for Android in order to use it. Here is the function that I have right now (copy / paste from the tutorial and strongly edit, so it is not readable. I will fix it when it really works.) Currently the list is displayed as empty. At least it's better than before, and it no longer crashes, though ...

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; } 
+4
source share
3 answers

In your code, at the time fstNmElmnt.toString () is added to gameList, this is the element corresponding to the game tag. Assuming your XML is structured by <name> Joe </name>, you need to get the value of the first child element (instead of calling toString () for the element itself):

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

By the way, if you do not have tags in other parts of your document, or if this element requires a <game> element for other processing, you can use the following (much simpler) code:

 NodeList nodeList = doc.getElementsByTagName("name"); for (int s = 0; s < nodeList.getLength(); ++s) { gamesList.add(nodeList.item(s).getFirstChild().getNodeValue()); } 
+1
source

Try using Simple :)

0
source

Robert Masaioli's answer gives an idea of โ€‹โ€‹using Simple.

It is important to remember that Simple XML must be able to follow any structure that you can logically generate using classes. That way, you can simply create a BaseClass that uses the error interface and apply the Decorator pattern so that it passes all of this through a specific error class without any implementing objects that needed to know what they were given.

That probably doesn't make sense. How about what I just show you ... okay ... I just left and implemented exactly what I was thinking about, and here are the results (full link to the code):

Main file:

package com.massaiolir.simple.iface;

import java.io.File;

import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister;

public class Main {public static void main (String [] args) throws Exception {Serializer serial = new Persister (); ResC resc = serial.read (ResC.class, new file ("data / testdata.xml"));

  System.out.println(" == Printing out all of the error text. == "); System.out.println(resc.getErrorText()); System.out.println(resc.conRes.getErrorText()); System.out.println(resc.conRes.conList.getErrorText()); for (Con con : resc.conRes.conList.cons) { System.out.println(con.getErrorText()); } System.out.println(" == Finished printing out all of the error text. == "); } 

} It is simple and displays the results.

BaseObject.java class:

package com.massaiolir.simple.iface;

import org.simpleframework.xml.Element;

The public class BaseObject implements Error {@Element (name = "Err", required = false, type = ConcreteError.class) private Error err;

 @Override public String getErrorText() { return err.getErrorText(); } @Override public void setErrorText(String errorText) { err.setErrorText(errorText); } 

} This is a class that must expand if it wants to "Err".

Error Interface:

package com.massaiolir.simple.iface;

open interface Error {void setErrorText (String errorText);

 String getErrorText(); 

} ConcreteError class:

package com.massaiolir.simple.iface;

import org.simpleframework.xml.Attribute;

Public class ConcreteError implements Error {@ Attribute private string text;

 @Override public String getErrorText() { return text; } @Override public void setErrorText(String errorText) { this.text = errorText; } 

} Actual implementation classes after this point. You will see that they are pretty trivial because the real work is handled in the classes above.

Con class:

package com.massaiolir.simple.iface;

Public class Con extends BaseObject {

} ConList class:

package com.massaiolir.simple.iface;

import java.util.ArrayList;

import org.simpleframework.xml.ElementList;

The public ConList class extends BaseObject {@ElementList (entry = "Con", inline = true) public ArrayList cons; } ConRes class:

package com.massaiolir.simple.iface;

import org.simpleframework.xml.Element;

The public class ConRes extends BaseObject {@Element (name = "ConList") public ConList conList; } ResC class:

package com.massaiolir.simple.iface;

import org.simpleframework.xml.Element; import org.simpleframework.xml.Root;

@root The public ResC class extends BaseObject {@Element (name = "ConRes") public ConRes conRes; } And thatโ€™s all there is. Pretty simple. I was able to break it all in ten minutes. In fact, it took me longer to write this answer than it took me to write the code that I give you. If you do not understand anything about the code I just wrote, please let me know. Hope this helps you understand how you can do something like this.

0
source

Source: https://habr.com/ru/post/1338375/


All Articles