I am relatively new to jaxb, having inherited something of a behemoth of an
application which uses it extensively.
A new requirement that has come up is the requirement that any comments in
the XML files used by the app must be preserved. At the moment, obviously,
they are getting eaten by the marshaling/marshaling process.
There seems to be a surprisingly little amount of information on this around
t'interweb, however, the Javadoc states that one can use a binder instead,
and that updateXML "preserves as much of original XML infoset as possible
(i.e. comments, PI, ...)", and also "unknown elements/attributes in XML that
were not bound to JAXB will be left untouched (whereas a marshalling
operation would create a new tree that doesn't contain any of those.)"
So far so hoopy. Except it doesn't seem to be doing anything of the sort.
This relatively simple chunk of code:
JAXBContext jaxbContext = JAXBContext.newInstance(packageName);
Binder binder = jaxbContext.createBinder();
File file = new File(xmlFileName);
if (!file.exists()) throw new FileNotFoundException();
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (file);
Item item = (Item) binder.updateJAXB(doc.getDocumentElement());
item.setName("changing name");
binder.updateXML(item);
Source source = new DOMSource(doc);
File outfile = new File(destinationName);
Result result = new StreamResult(outfile);
Transformer xformer =
TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
yields a new XML file which contains exactly what it would have contained if
I'd just used the bog standard Marshaller/unmarshaller objects. As soon as
updateXML is called, any unknown attributes and all comments are stripped.
Oddly, I also seem to lose carriage returns after each line.
As I said at the beginning, I don't really understand JAXB all that well yet
so it's eminently possible that I could be doing something dim. Is that the
case, or should this work?
--
View this message in context: http://www.nabble.com/Using-JAXB-binder-to-preserve-%3C%21---comments---%3E-tp25240384p25240384.html
Sent from the java.net - jaxb users mailing list archive at Nabble.com.