问题
How to unmarshal and marshal a XML file without losing the comments? Is any way is there using JAXB, I tried example using following link but it doesn't work from 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 unmarshal the above xml, add a new address to it and marshall it back without losing the following the comments.
<!-- comments line 1 -->
<!-- comments line 2-->
回答1:
You could use JAXB in combination with StAX to get access to the trailing 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();
}
}
}
回答2:
Perhaps it's easier to adapt / extend your (data)model of customer-addresses.
<customer>
<billing-address>
<street></street>
<street></street>
<city></city>
</billing-address>
<shipping-address>
<street></street>
<street></street>
<street></street>
<city></city>
</shipping-address>
</customer>
This way the semantic is in the model not 'hidden' in comments.
回答3:
@Hareesh in order to preserve comments in your XML file using the example you provided you need to use 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 the document object that your read from the XML file and use the binder updateXML method to marshall back your objects into the document object before writing it to the XML file.
The reason this works is that the comments are maintained in the document object, not the JAXB object. You should also look at the updateJAXB method (if you decide to update the document object).
If you post the code that does not work we could help better.
来源:https://stackoverflow.com/questions/25717436/how-to-preserve-xml-comments-with-jaxb