How to save XML comments in JAXB?

How to unmount and output an XML file without losing comments? Is there any way to use JAXB, I tried using the following link but this does not work for me.

<customer> <address> <!-- comments line 1 --> <street>1 Billing Street</street> </address> <address> <!-- comments line 2--> <street>2 Shipping Road</street> </address> </customer> 

I want to unmount the above xml, add a new address to it and cancel it without losing the following comments.

 <!-- comments line 1 --> <!-- comments line 2--> 
+2
source share
3 answers

You can use JAXB in conjunction with StAX to access the final comment.

 import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource source = new StreamSource("pathOfYourXML/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(source); JAXBContext jc = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); Customer xml = (Customer) unmarshaller.unmarshal(xsr); while(xsr.hasNext()) { if(xsr.getEventType() == XMLStreamConstants.COMMENT) { System.out.println(xsr.getText()); } xsr.next(); } } } 
0
source

It may be easier for you to adapt / expand your (data) client address model.

 <customer> <billing-address> <street></street> <street></street> <city></city> </billing-address> <shipping-address> <street></street> <street></street> <street></street> <city></city> </shipping-address> </customer> 

Thus, the semantics in the model are not “hidden” in the comments.

0
source

@Hareesh To save comments in your XML file using the example you provided, you need to use the DOM (document object model) to read and write the XML file, not JAXB (as in the example). However, you can use the javax.xml.bind.Binder class to unmarshall your objects from a document object that you are reading from an XML file, and use the binder updateXML method to marshal your objects into a document object before writing it to an XML file.
The reason this works is because comments are supported in the document object, not in the JAXB object. You should also take a look at the updateJAXB method (if you decide to update the document object). If you post code that doesn't work, we could help better.

0
source

Source: https://habr.com/ru/post/1206421/


All Articles