Using Moxy as JAXB Implementation and setting jaxb.properties with more than one POJO package

时光怂恿深爱的人放手 提交于 2019-12-06 11:26:57

I am trying this, because the default implementation included in the JDK seems to have a hard coded indentation level of eight with UTF-8 encoding.

The JAXB reference implementation does have an extension property that allows you to control indenting:


As far as jaxb.properties, when dealing with multiple packages with a single JAXBContext only one of the packages needs to include the jaxb.properties file.

There are a few different things that can be done to make your use of MOXy easier:

Use MOXy's XJC Wrapper

MOXy offers a script that wraps XJC that will add the jaxb.properties file in the appropriate spot.

<ECLIPSELINK_HOME>/bind/jaxb-compiler.sh

Make MOXy the Default JAXB Provider in Your Environment

You could also leverage the META-INF/services mechanism to specify MOXy as the default JAXB provider:

  1. Create a JAR that contains a file called javax.xml.bind.JAXBContext in the directory META-INF/services
  2. The contents of the javax.xml.bind.JAXBContext file must be org.eclipse.persistence.jaxb.JAXBContextFactory
  3. Add that jar to your classpath.

Use the Native MOXy API

import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContextFactory.createContext("com.example.pkg1:org.example.pkg2", null, null);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("input.xml");
        Object object = unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(object, System.out);
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!