Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get formatted xml output from jaxb in spring?

Tags:

spring

jaxb

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>
like image 376
outvir Avatar asked Feb 03 '11 05:02

outvir


4 Answers

<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>
like image 116
Ritesh Avatar answered Nov 17 '22 16:11

Ritesh


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.

like image 23
jmort253 Avatar answered Nov 17 '22 16:11

jmort253


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;
}
like image 11
DeezCashews Avatar answered Nov 17 '22 16:11

DeezCashews


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>
like image 8
Doppelganger Avatar answered Nov 17 '22 16:11

Doppelganger