JAXB Fragment Marshal w/o namespace

前端 未结 3 816
时光说笑
时光说笑 2021-02-05 21:18

I\'m using the JAXB_FRAGMENT property for my marshaller to marshal at the WorkSet level. The problem is that when I marshal it\'s giving the WorkSet element the xmlns attribute

3条回答
  •  花落未央
    2021-02-05 21:26

    Assuming you want the default namespace for your document to be http://www.namespace.com, you could do the following:

    Demo

    The XMLStreamWriter.setDefaultNamespace(String) and XMLStreamWriter.writeNamespace(String, String) methods will be used to set and write the default namespace for the XML document.

    package forum9297872;
    
    import javax.xml.bind.*;
    import javax.xml.stream.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
            writer.setDefaultNamespace("http://www.namespace.com");
    
            JAXBContext jc = JAXBContext.newInstance(WorkSet.class);
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    
            writer.writeStartDocument();
            writer.writeStartElement("http://www.namespace.com", "Import");
            writer.writeNamespace("", "http://www.namespace.com");
            writer.writeStartElement("WorkSets");
    
            m.marshal(new WorkSet(), writer);
            m.marshal(new WorkSet(), writer);
    
            writer.writeEndDocument();
            writer.close();
        }
    
    }
    

    WorkSet

    My assumption is that you have specified namespace information in your JAXB model.

    package forum9297872;
    
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="WorkSet", namespace="http://www.namespace.com")
    public class WorkSet {
    
    }
    

    Output

    Below is the output from running the demo code:

    
    

提交回复
热议问题