1

I am creating a little board game in Java, and I want to implement the game levels in a XML file (ie for each level, the level id, the height and length of the board, and the definition of each cells), and then construct the board by asking the user the level he wants to play.

I already build a classical constructor in the Board class, without the XML file and with a if (so i put every level descriptions in the code). The problem is that every time I want to add a level, I need to compile again.

Thanks !

2 Answers2

1

Take a look at this page to see how it's done in Java: Java XML Parsers. There are about four different parsers builtin Java (maybe more in newer versions).

Now regarding the constructor:

public Board(String pathToXML) {
   // Add code parsing the XML
}

You could send the parameter as a argument to the main method, before you call the constructor.

public static void main(String[] args) {
    String pathToXML = args[0];
    Board b = new Board(pathToXML);
}

Remember that arguments starts from 0, not 1.

1

Short answer: do not try to parse an XML file in your board constructor.

You already seem to have a working constructor and valid classes to setup the board for you. Pass these classes to the Board constructor. Let some kind of factory create the instances for you.

Do not mix the XML-parsing logic with the Board game logic. That's two completely different things. According to the single-responsibility rule, it should be kept separate.

Done correctly, you should be able to create a board with an ad-hoc configuration in code, from an XML-File or any other source. In other words: It should not matter for the board where the data came from.

The XML file should look more like this:

<Levels>
    <Level id="1">
    <h>2</h>
    <l>2</l>
    <plateau key="value">
      <cells>
        <cell row="0" column="0" color="black">
        </cell>
        <!-- ... -->
      </cells>
    </plateau>

Use an XML parser to parse the read the data from the file. Pass the result to the Board constructor, e.g. pseudo code:

List<Level> levels = parseLevels(...);
new Board(levels.get(0));

The implementation of 'parseLevels()' might be tricky. I recommend you use JAXB to parse the file and create your data structure. Try this tutorial: https://www.baeldung.com/jaxb

Jochen Reinhardt
  • 833
  • 5
  • 14
  • Thanks, I understand the problem, but do you have any clue on how to implement this. Indeed, all the program I coded in Java were with constructors built in a class – JavaLearner May 13 '19 at 10:14
  • I see, you are actually trying to write java code in your XML file. That's not the way to go, IMHO. You should add some true structure to your XML file. The cell and plateau seem to be central elements in your domain model. You should have these as elements in your XML document, too. – Jochen Reinhardt May 13 '19 at 10:34