I need to apply some treatment (such as double space removal )in all the elements in the XML file. I am using moxy implementation of jaxb. Is it possible to implement the same in jaxb.
You could use the CollapsedStringAdapter
to clean up your strings (or create your own). If you want it applied to all String
field/properties within a package you can specify this XmlAdapter
using @XmlJavaTypeAdapter
at the package level.
package-info
@XmlJavaTypeAdapter(value=CollapsedStringAdapter.class, type=String.class)
package forum17484029;
import javax.xml.bind.annotation.adapters.*;
Demo
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum17484029/input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
input.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<foo> A B C </foo>
<bar> X Y Z </bar>
</root>
Output
<?xml version="1.0" encoding="UTF-8"?>
<root>
<foo>A B C</foo>
<bar>X Y Z</bar>
</root>
For More Information