开发者

Java SAX ContentHandler to create new objects for every root node

I am using SAX to parse some XML. Let's say I have the following XML document:

<queue>
   <element A> 1 </element A>开发者_C百科;
   <element B> 2 </element B>
</queue>
<queue>
   <element A> 1 </element A>
   <element B> 2 </element B>
</queue>
<queue>
   <element A> 1 </element A>
   <element B> 2 </element B>
</queue>

And I also have an Elements class:

public static Elements {

  String element;

  public Elements() {

  }

  public void setElement(String element){
     this.element = element;
  }

  public String getElement(){
     return element;
  }

}

I am looking to write a ContentHandler that follows the following algorithm:

Vector v;
for every <queue> root node {
   Element element = new Element();

   for every <element> child node{
      element.setElement(value of current element);
   }
   v.addElement(element);
}

So, I want to create a bunch of Element objects and add each to a vector...with each Element object containing its own String values (from the child nodes found within the root nodes.

I know how to parse out the elements and all of those details, but can someone show me a sample of how to structure my ContentHandler to allow for the above algorithm?

Thanks!


You can not write the handler with loop as you suggested. It's really event-based, so you need to keep track of the currentQueue and currentElement yourself in your handler. Beware also that characters may be called more than once per tag (there are other questions about this point).

So here is a very rough sketch:

Queue currentQueue;
Element currentElement;

startElement(node){
  if( node is queue )
     currentQueue = new Queue();
  else if( node is element )
     currentElement = new Element(); 
}

characters( chars ) {
  currentElement.setName( chars );
}

endElement(node){
  if( node is queue )
     currentQueue = null;
  else if( node is element ) {
     currentQueue.add( currentElement ); <-- that's the important part
     currentElement = null; 
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜