我遇到同样的问题:
JAXB :Need Namespace Prefix to all the elements
但是,我必须使用特定的命名空间。然后我将package-info.java更改为:
@XmlSchema(
namespace = "www.example.com/a",
elementFormDefault = XmlNsForm.UNQUALIFIED,
xmlns={@XmlNs(prefix="pre", namespaceURI="www.example.com/a")})
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
我通过以下方式执行示例:
public class Test {
public static void main(String[] args)
throws JAXBException, XMLStreamException, FactoryConfigurationError {
ObjectFactory o = new ObjectFactory();
Login l = o.createLogin();
l.setPassword("abc");
l.setUsername("abc");
JAXBContext jc = JAXBContext.newInstance(l.getClass());
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(l, System.out);
}
}
但是,我在package-info中设置了前缀“ns2”而不是“pre”:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Login xmlns:ns2="www.example.com/a">
<username>abc</username>
<password>abc</password>
</ns2:Login>
然后我尝试了一个快捷方式: Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance()
.createXMLStreamWriter(System.out);
xmlStreamWriter.setPrefix("pre", "www.example.com/a");
m.marshal(l, xmlStreamWriter);
如果用一只手添加前缀。另一方面,名称空间不包含在xml中: ABCABC
我期待的是: ABC ABC
更新:
我可以在另一个问题中找到答案:
What happened to JAXB's NamespacePrefixMapper in JDK6u18
我需要一个JABX RI。并扩展NamespacePrefixMapper并将其添加到masherller,我可以使用正确的前缀生成xml。