Reputation: 320
I am working on an xml writer for a format conversion. I decided to use the StAX API (the cursor API to be exact) because of the streaming capabilities (the input file is quite large and needs to be written segment by segment). I am using a data format (some classes) to store the parsed values from the input file. I also created some classes for the writing of the xml file , that have a writeNode method. This method looks like this:
public void writeNode(Object object){
writer.writeStartElement();
... some writeNode calls of the children nodes
writer.writeEndElement();
}
The object with the name "writer" is an instance of the StAXStreamWriter class. My problem is, that sometimes these children nodes are empty. In these cases the parent nodes should not be written at all. Right now I am generating empty nodes, because the start tag of the current node is already be written. As far as i know this cannot be reversed. Any ideas to solve this problem?
best regards
Lars
Update:
I think, I found a solution. I will write my own class, that implements the XMLStreamWriter interface. In this class I will use a queue or list data structure to store the start tags until the first attribute or node value is written.
Update 2:
Here is a more precise description of my solution. I used the decorator design pattern in order to wrap my new class around the standard streamwriter class. This class has an ArrayList, in which the Start Tags are stored until a writeCharacter method is called.
Upvotes: 0
Views: 1097
Reputation: 1040
when going though the XML File, you can get the current Event by xmlStreamReader.getEventType()
. When you encounter XMLStreamConstants.START_ELEMENT
, you could keep the opening Tag-Names, for instance in an Collection that keeps the insertation order (like LinkedHashSet
).
When you then encounter XMLStreamConstants.CHARACTERS
, do a .getText()
and write the previously stored Tags to the xmlStreamWriter
, but only if this Text is not empty (maybe you also want to .trim()
the .getText()
-Result).
Regards, Max
Upvotes: 1