I have an XML document (generated by Adobe XFA forms), that contains data like the following:
<Position>
<PositionBorder>
<Title/>
<StartDate/>
<EndDate/>
</PositionBorder>
</Position>
Since this file is defined elsewhere, I am not at liberty to change the format of the XML that I get.
In my Java code, I create a Position class that contains the Title, Start and End Dates.
My problem is, when I use XStream to parse the file, it wants a PositionBorder class to hold the title and dates. I want to basically ignore the border and place all of the fields into the Position class.
What I'd really like to do is use something like the convertAnother method to convert the child of the position element. I tried to do just that and it fails, because my PositionConverter gets called for the PositionBorder (when I call convertAnother).
Anyone have any clues how to deal with collapsing the structure of an XML when parsing?
It's not terribly difficult to do with a custom converter. This is a little bit of a long example, but I hope it's simple enough to get the gist of what you need to do:
Try running that and see what happens. You'll need to modify it to suit your own types, of course -- I just used strings for all of Position's fields (and I'm sure you're Position class isn't nested, either), but converting from a String to a Date (or whatever) should be rather trivial.
One thing you'll want to keep an eye on (and I might not have gotten it completely right in my example) is matching your reader.moveDown() and reader.moveUp() calls. (And, if you're going to do any marshalling instead of just unmarshalling -- which I don't expect from your question -- you'll want to match your writer.startNode() and writer.endNode() calls as well.) It probably won't cause any problems with this example, but I'm sure it'll raise issues if you're doing anything larger or processing multiple files with the same XStream or Converter instance. Also, if you try reader.moveDown() from an invalid location, you'll get a really ugly exception -- it should be pretty obvious.
I had to play around with the moveUp/moveDown methods a bit to get them in the right places, so I'm sure you'll need to test it and tweak it until you get what you need.
I find this way more easy to use: