views:

245

answers:

3

I have to parse some xml with java SAX parser. As I was busy, I saw that the state pattern could be used here.

There are clear states and state transitions defined, resembling the structure of the xml document.

To implement the state pattern, I have to define a interface (or abstract class). The most obvious interface methods would be:

public void startElement(String elementName);
public void endElement(String elementName);

But the problem I encounter is how to return the information. I need the information from several levels in the xml document in one structure.

This is a part of the xml document

<chessboard>
     <white>
         <king>
              <position>
                  <x>e</x>
       <y>1</y>
              </position>
         </king>
         <pawns>
             <pawn id="1">
                  <position>
                      <x>e</x>
           <y>2</y>
                  </position>
             </pawn>
             <pawn id="1">
                  <position>
                      <x>f</x>
           <y>2</y>
                  </position>
             </pawn>
         </pawns>
    </white>
</chessboard>

Is my assumption right that the state patterns fits here? And if so, what is the best way to implement it here?

+2  A: 

Your interface could be implemented by classes whose instances "internally accumulate" the specific required information, and add other methods to make that information accessible.

However, it's difficult to have general-purpose "get the info" methods, since types can vary; and, this whole approach may not fit well with the main advantage of SAX-like approaches, which is the ability to perform actions incrementally as the parse proceeds, rather than accumulating info during the parse and only acting later (this advantage can be crucial when you're parsing extremely large documents). So, I wouldn't take it as a "canonical" way to employ SAX in Java, just as one variation which may come in handy once in a while.

Alex Martelli
You got me thinking. I could just pass a class to each method of the state class, and the stateclasses could just alter that class.Even with the normal approach to SAX, you would have to keep some state.
Ikke
A: 

I think state pattern just fits here. There has to be some state kept, to know where you are in the document.

To gather the information, you can pass an object to each method of the stateclasses, so they can put their information in there.

Unless there is some other problem I haven't thought of, I think this is the best sollution.

Ikke