1. 先下载 JAXB-RI, 确保 jaxb-impl-x.x.x.jar 位于你的classpath下,且优先于JDK的RT.jar
2. 参考使用以下代码:
- import java.io.BufferedOutputStream;
-
import java.io.FileNotFoundException;
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
-
import javax.xml.bind.JAXBContext;
-
import javax.xml.bind.JAXBException;
-
import javax.xml.bind.Marshaller;
-
import javax.xml.stream.XMLStreamException;
-
import javax.xml.transform.TransformerException;
-
-
import me.test.persons.Person;
-
import me.test.persons.Persons;
-
-
import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
-
-
public class CustomJAXBPrefix {
-
-
public static void main(String[] args) throws Exception {
-
marshal();
- }
-
-
public static void marshal() throws JAXBException, XMLStreamException,
-
FileNotFoundException, TransformerException {
-
// Step 1.
-
Persons ps = new Persons();
-
Person p = new Person();
-
p.setAge(12);
-
p.setName("btpka3");
-
p.set***("man");
-
ps.getPerson().add(p);
-
-
JAXBContext context = JAXBContext.newInstance(Persons.class);
-
Marshaller marshaller = context.createMarshaller();
-
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
-
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
-
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
-
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
-
new MyNamespacePrefixMapper());
-
-
marshaller.marshal(ps, System.out);
-
System.out.println();
-
}
-
public static class MyNamespacePrefixMapper extends NamespacePrefixMapper {
-
@Override
-
public String getPreferredPrefix(String namespaceUri,
-
String suggestion, boolean requirePrefix) {
-
if (requirePrefix) {
-
if ("".equals(namespaceUri)) {
-
return "me";
-
}
-
return suggestion;
-
} else {
-
return "";
-
}
-
}
-
}
- }
阅读(2833) | 评论(0) | 转发(0) |