If my XML processor is written with the gxml API, it can operate over any tree model for which it has a gxml bridge. But if required to produce a specific type of tree model, perhaps to provide data to a legacy, non-gxml application, I may need to convert my underlying node tree to the type which the legacy application requires. As long as I have a bridge to that desired tree model, that conversion will be a piece of cake.
In this sample, I’ll demonstrate such a conversion from an XmlNode, the node type for the gxml reference bridge, to a DOM Node. I’ll start with a convenience method for handling generic node conversions. The crux of this conversion is the creation of a cursor over the source <Nsrc> node, and a builder for the target <Ntrgt> node. Then, I simply write the content of the cursor to the builder:
final static public Ntrgt untypedConversion(final Nsrc srcNode,
final ProcessingContext srcPcx, final ProcessingContext trgtPcx) {
final Cursor srcCursor = srcPcx.newCursor(srcNode);
final FragmentBuilder trgtBuilder = trgtPcx.newFragmentBuilder();
srcCursor.write(trgtBuilder);
return trgtBuilder.getNode();
}
In order to inject the specific source and target node types, I’ll write a concrete implementation, wherein the injection is managed solely by the creation of appropriate processing contexts for each type of node:
static public void main(String[] args) {
ProcessingContext cxContext = new XmlNodeContext();
ProcessingContext domContext = new DomProcessingContext();
SampleConverter.convertSample(args[0], cxContext, domContext);
}
The source code for this example can be downloaded from our developer site, and this particular example lives in the samples project, in the SampleSerializer and Cx2DomSampleConverter classes.