jaxb实体转xml命名空间的问题(备忘)

使用jaxb将pojo转为xml,一点问题也没有,唯独不完美的是不是理想的命名空间。

于是看api ,写了一个点小东西。

转换的代码:

//from  xml  2  object
 public  static  void  Object2Xml(Object paramObject, NamespacePrefixMapper paramNamespacePrefixMapper, OutputStream paramOutputStream)throws JAXBException{
  Class localClass = paramObject.getClass();
     JAXBContext localJAXBContext = JAXBContext.newInstance(new Class[] { localClass });
     Marshaller localMarshaller = localJAXBContext.createMarshaller();
     localMarshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", paramNamespacePrefixMapper);
     localMarshaller.setProperty("jaxb.formatted.output", Boolean.valueOf(true));
     localMarshaller.marshal(paramObject, paramOutputStream);
 };

然后再写一个类:

public class MessageOutPutNamespacePrefixMapperImpl extends NamespacePrefixMapper implements Serializable {
 private static final long serialVersionUID = 9056869566627080889L;
 @Override
 public String getPreferredPrefix(String namespaceUri, String suggestion,
   boolean requirePrefix) {
  if( "http://www.w3.org/2001/XMLSchema-instance".equals(namespaceUri) )
            return "xsi";
        
        if( "http://www.geostar.com.cn/geoglobe".equals(namespaceUri) )
            return "geoglobe";
       
        if( "http://www.opengis.net/gml".equals(namespaceUri) )
            return "gml";
           
        return suggestion;
 }
 
 public String[] getPreDeclaredNamespaceUris() {
  return new String[] {null};
 }
}

使用:JaxbUtil.Object2Xml(response, new MessageOutPutNamespacePrefixMapperImpl(), baos);

生成的xml:

  <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <geoglobe:MessageOutput xmlns:geoglobe="http://www.geostar.com.cn/geoglobe" count="0">
        <geoglobe:Message>查询无记录</geoglobe:Message>
        <geoglobe:Type>failure</geoglobe:Type>
  </geoglobe:MessageOutput>

 

转载请注明出处:http://www.cnblogs.com/likehua

posted @ 2011-09-28 17:00  李克华  阅读(995)  评论(0)    收藏  举报