How to get formatted xml output from jaxb in sprin

2019-02-05 13:41发布

I am using Jaxb2Marshaller as a view property for ContentNegotiatingViewResolver. I am able to get the xml repsonse. How do I format (pretty print) it?

<bean
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
        <map>
            <entry key="xml" value="application/xml" />
        </map>
    </property>
    <property name="defaultViews">
        <list>

            <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                <constructor-arg>
                    <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                        <property name="classesToBeBound">
                            <list>

                            </list>
                        </property>
                    </bean>
                </constructor-arg>
            </bean>
        </list>
    </property>

</bean>

标签: spring jaxb
5条回答
手持菜刀,她持情操
2楼-- · 2019-02-05 14:21

Was looking for this and thought I'd share the code equivalent

@Bean
public Marshaller jaxbMarshaller() {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    Jaxb2Marshaller m = new Jaxb2Marshaller();
    m.setMarshallerProperties(props);
    m.setPackagesToScan("com.example.xml");
    return m;
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-02-05 14:31

Try setting this property on your marshaller object:

 marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE )

Here is the full Javadoc for the Marshaller interface. Check out the Field Summary section.

查看更多
看我几分像从前
4楼-- · 2019-02-05 14:45

Ritesh's answer didn't work for me. I had to do the following:

<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list> ... </list>
    </property>
    <property name="marshallerProperties">
        <map>
            <entry key="jaxb.formatted.output">
                <value type="boolean">true</value>
            </entry>
        </map>
    </property>
</bean>
查看更多
走好不送
5楼-- · 2019-02-05 14:47
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list> .... </list>
    </property>
    <property name="marshallerProperties">
        <map>
            <entry>
                <key>
                    <util:constant static-field="javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT" />
               </key>
              <value type="java.lang.Boolean">true</value>
            </entry>
        </map>
    </property>
</bean>
查看更多
甜甜的少女心
6楼-- · 2019-02-05 14:47

Use jaxb.formatted.output instead of javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT as

Map<String,Object> map = new HashMap<String,Object>();
map.put("jaxb.formatted.output", true);
jaxb2Marshaller.setMarshallerProperties(map);
查看更多
登录 后发表回答