Chinaunix首页 | 论坛 | 博客
  • 博客访问: 518544
  • 博文数量: 135
  • 博客积分: 3568
  • 博客等级: 中校
  • 技术积分: 1942
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-19 17:52
文章分类

全部博文(135)

文章存档

2012年(29)

2011年(41)

2010年(26)

2009年(12)

2008年(9)

2007年(12)

2006年(6)

分类: Java

2011-06-11 14:17:30

1. 先下载 JAXB-RI, 确保 jaxb-impl-x.x.x.jar 位于你的classpath下,且优先于JDK的RT.jar
2. 参考使用以下代码:
  1. import java.io.BufferedOutputStream;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;

  5. import javax.xml.bind.JAXBContext;
  6. import javax.xml.bind.JAXBException;
  7. import javax.xml.bind.Marshaller;
  8. import javax.xml.stream.XMLStreamException;
  9. import javax.xml.transform.TransformerException;

  10. import me.test.persons.Person;
  11. import me.test.persons.Persons;

  12. import com.sun.xml.bind.marshaller.NamespacePrefixMapper;

  13. public class CustomJAXBPrefix {

  14.     public static void main(String[] args) throws Exception {
  15.         marshal();
  16.     }

  17.     public static void marshal() throws JAXBException, XMLStreamException,
  18.             FileNotFoundException, TransformerException {
  19.         // Step 1.
  20.         Persons ps = new Persons();
  21.         Person p = new Person();
  22.         p.setAge(12);
  23.         p.setName("btpka3");
  24.         p.set***("man");
  25.         ps.getPerson().add(p);

  26.         JAXBContext context = JAXBContext.newInstance(Persons.class);
  27.         Marshaller marshaller = context.createMarshaller();
  28.         marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  29.         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  30.         marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
  31.         marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
  32.                 new MyNamespacePrefixMapper());

  33.         marshaller.marshal(ps, System.out);
  34.         System.out.println();
  35.     }
  36.     public static class MyNamespacePrefixMapper extends NamespacePrefixMapper {
  37.         @Override
  38.         public String getPreferredPrefix(String namespaceUri,
  39.                 String suggestion, boolean requirePrefix) {
  40.             if (requirePrefix) {
  41.                 if ("".equals(namespaceUri)) {
  42.                     return "me";
  43.                 }
  44.                 return suggestion;
  45.             } else {
  46.                 return "";
  47.             }
  48.         }
  49.     }
  50. }

阅读(2796) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~