javaxmljdomdom4jxom

Java XML Reading an XML file from top to bottom


I want to read an XML starting from the top to the bottom using Java. However, I don't want to use recursive functions because I want to be able to jump to a different element and start reading from that position.

I've tried using getParent() and indexOf() methods (All three libraries below have these methods) to do this, but it's gotten very messy, mainly because the methods don't distinguish between attributes and elements.

I'm sure there must be a simple way to do this, but after trying dom4j, jdom, and xom, I still have not found a solution.

[Edit] More Information:

My friend wants to make a console text-based game in a question/answer type style. Instead of hard-coding it into java, I decided to try and make it read an XML file instead, because XML has a tree-like style that would be convenient. Here is an example of what my XML file might look like:

<disp>Text to be displayed</disp>
<disp>Text to be displayed afterward</disp>
<disp>What is your favorite color?</disp>
<question>
    <answer name="orange">
        <disp>Good choice.</disp>
        <!-- More questions and stuff -->
    </answer>
    <default>
        <disp>Wrong. The correct answer was orange.</disp>
    </default>
</question> 

I don't know if it taboo to use XML like an pseudo programming language. If anyone has other suggestions feel free to give them.


Solution

  • Your design is basically good and an example of Declarative Programming. You should read your XML files using an XML parser either into a DOM or using SAX. Since I think you will want to revisit nodes I suspect you will need a DOM (FWIW I use XOM, xom.nu). One of the best examples of XML-based declarative programming is XSLT where the data and commands are all XML.

    I use this model a great deal. It has the advantage that the data structure can be external and can be edited.

    (Note that your XML needs a root element)

    but it's gotten very messy, mainly because the methods don't distinguish between attributes and elements.

    All DOM or SAX tools differentiate very clearly between attributes and elements, so if there is confusion it is somewhere else.