2011-02-03 81 views
27

我正在使用Jaxb2Marshaller作爲ContentNegotiatingViewResolver的視圖屬性。我能夠得到xml repsonse。我如何格式化(漂亮的打印)呢?如何在spring中從jaxb獲取格式化的xml輸出?

<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> 

回答

36
<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> 
+0

謝謝,那就是訣竅。 – outvir 2011-02-04 02:21:23

21

試試你的編組對象上設置該屬性:

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

下面是Marshaller接口完整的Javadoc。查看Field Summary部分。

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> 
2

一直在尋找這個,以爲我會分享代碼相當於代替javax.xml.bind.Marshaller

@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; 
} 
0

使用jaxb.formatted.output。 JAXB_FORMATTED_OUTPUT as

Map<String,Object> map = new HashMap<String,Object>(); 
map.put("jaxb.formatted.output", true); 
jaxb2Marshaller.setMarshallerProperties(map);