JAXB marshalling XMPP stanzas

匿名 (未验证) 提交于 2019-12-03 02:01:02

问题:

I am trying to marshall a message using the following snippet:

        JAXBContext jContext = JAXBContext.newInstance(Iq.class);         Marshaller m = newJAXBContext.createMarshaller();         m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);         m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);          Bind bind = new Bind();         bind.setResource("resource");         Iq iq = new Iq();         iq.setId(iqId);         iq.setType("set");         iq.getAnies().add(bind);          ByteArrayOutputStream baos = new ByteArrayOutputStream();         m.marshal(iq, baos);

Here, Iq and Bind are the objects formed from the relevant xmpp schemas. My problem is, with jaxb 2.0 and later versions, all the namespaces are declared in the root element:

               resource      

But, what is needed here is that the namespaces should occupy the appropriate places:

                      resource         

Is there a way to marshall the xmpp stanzas as you see them in the 2nd xml stanza through JAXB 2.0 or later versions?

Long story short, I have 2 problems here: 1. Declaring the namespaces at appropriate locations. 2. removing the namespace prefix which I understand can be removed using the NamespacePrefixMapper? Not sure though, an example would be great.

回答1:

How about the following?:

Create a custom XMLStreamWriter that will treat all namespace declarations as default namespaces, and then marshal to that:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out); xsw = new MyXMLStreamWriter(xsw); m.marshal(iq, xsw); xsw.close();

MyXMLStreamWriter

import java.util.Iterator;  import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter;  public class MyXMLStreamWriter implements XMLStreamWriter {      private XMLStreamWriter xsw;     private MyNamespaceContext nc = new MyNamespaceContext();      public MyXMLStreamWriter(XMLStreamWriter xsw) throws Exception {         this.xsw = xsw;         xsw.setNamespaceContext(nc);     }      public void close() throws XMLStreamException {         xsw.close();     }      public void flush() throws XMLStreamException {         xsw.flush();     }      public NamespaceContext getNamespaceContext() {         return xsw.getNamespaceContext();     }      public String getPrefix(String arg0) throws XMLStreamException {         return xsw.getPrefix(arg0);     }      public Object getProperty(String arg0) throws IllegalArgumentException {         return xsw.getProperty(arg0);     }      public void setDefaultNamespace(String arg0) throws XMLStreamException {         xsw.setDefaultNamespace(arg0);     }      public void setNamespaceContext(NamespaceContext  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!