如何在spring中从jaxb获取格式化的xml输出?

out*_*vir 29 spring jaxb

我使用Jaxb2Marshaller作为ContentNegotiatingViewResolver的视图属性.我能够得到xml repsonse.我如何格式化(漂亮打印)呢?

<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>
Run Code Online (Sandbox Code Playgroud)

Rit*_*esh 39

<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>
Run Code Online (Sandbox Code Playgroud)


jmo*_*253 22

尝试在marshaller对象上设置此属性:

 marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE )
Run Code Online (Sandbox Code Playgroud)

这是Marshaller接口的完整Javadoc .查看"字段摘要"部分.


Dop*_*ger 8

Ritesh的回答对我不起作用.我必须做以下事情:

<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>
Run Code Online (Sandbox Code Playgroud)


Dee*_*ews 7

寻找这个,以为我会分享等效的代码

@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;
}
Run Code Online (Sandbox Code Playgroud)