2

I have the same problem of:

JAXB :Need Namespace Prefix to all the elements

however, I have to use a specific namespace. Then I change the package-info.java to:

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

I execute the example by:

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);
}
}

However, my result has the prefix "ns2" instead of "pre" as I set in the package-info:

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

Then I tried a shortcut, by doing: 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);

If in one hand it adds the prefix. In other hand, the name space is not included in the xml: abcabc

What I was expecting is some like: abc abc

UPDATE:

I could find the answer in another question:

What happened to JAXB's NamespacePrefixMapper in JDK6u18

I need a JABX RI. And extending the NamespacePrefixMapper and adding it to the masherller, I can generate the xml with the correct prefix.

Community
  • 1
  • 1
user1032817
  • 23
  • 1
  • 8

0 Answers0