문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

It would be good if you would show what you want to do with the XML snippets, but normally if you want to read off of any kind of file, use java.util.Scanner.

Scanner scan = new Scanner (new File("file.xml"));
while (scan.hasNext()) {
    String theData = scan.nextLine();
}
scan.close();

This should return the values that you need until it runs out of lines to scan. Hope it works and Happy Coding!

Since you want to read a xml file. I recommend go for SAX parser. It is event based parser very fast and efficient for xml reading (top down approach).

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/ will explain about usage of sax parser.

Thanks

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top