Controlling namespace prefixes in JAXB

前端 未结 5 784
无人及你
无人及你 2020-12-03 12:05

How does jaxb determine the list of namespace prefix declarations whem marshalling an object? I used xjc to compile java classes for ebics (ebics schema). When I create an i

5条回答
  •  我在风中等你
    2020-12-03 12:54

    I generated my JAXB classes using xjc, but the SOAP WebService i am using force me to follow some rules, like not using namespace prefix.

    This is invalid:

    
         123
         
             
         
    
    

    This is valid:

    
        123
        
            
         
    
    

    As pointed out, JAXB put the namespace declaration at the root element.

    To overcome this, the first approach i use is to avoid unnecessary elements in the context.

    For example, setting the context of the marshaller like this:

    JAXBContext.newInstance("path.to.package");
    

    Can lead JAXB to make some unncessary declarations of namespaces.

    Sometimes, i can get ride of an annoying xmlns="http://www.w3.org/2000/09/xmldsig#" just setting the context with the necessary Root Element:

    JAXBContext.newInstance(MyRootElement.class);
    

    A second approach i use when the first is not enough, is to make the entire context use the same namespace. Just changing the unwanted "http://www.w3.org/2000/09/xmldsig#", in every namespace declaration (like @XmlElement or @XSchema), to the unique namespace allowed (http://www.portalfiscal.inf.br/nfe)

    Then, i just create an attribute at the desired child:

    @XmlAttribute(name="xmlns")
    String xmlns = "http://www.w3.org/2000/09/xmldsig#";
    

    Now i have the namespace declaration out of the root, in the correct element, without using any prefix.

提交回复
热议问题