使用JAXB从XML创建POJO

时间:2017-09-26 15:12:44

标签: java xml soap jaxb

我正在尝试使用Pojo to XML库转换JAXB

我需要最终结果看起来像这样:

<soap:Envelope 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>

 <!--other stuff-->

</soap:Body>
</soap:Envelope>

我尝试了几种不同的方法但到目前为止我没有成功,这是我最近的尝试。

@XmlRootElement(name = "soap:Envelope")
public class Envelope {

  private SoapBody soapBody;

  public String toString() {
      return "ClassPojo [SoapBody = " + soapBody + "]";
  }

  public SoapBody getSoapBody() {
      return soapBody;
  }

  @XmlElement(name = "soap:Body")
  public void setSoapBody(SoapBody soapBody) {
      this.soapBody = soapBody;
  }
}

这将转换为以下结果(但它缺少XMLNS行):

<soap:Envelope>
<soap:Body>
<!--Other stuff-->
</soap:Body>
</soap:Envelope>

我尝试在声明中添加名称空间标记:

@XmlRootElement(name = "soap:Envelope", namespace = "soap")

但它只是将该行转换为此<ns2:soap:Envelope xmlns:ns2="soap">

编辑:

    OutputStream os = connection.getOutputStream();
    JAXBContext jaxbContext = 
        JAXBContext.newInstance(MyOtherStuffObject.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(myObject, os);
    os.flush();

2 个答案:

答案 0 :(得分:1)

  

我尝试在声明中添加名称空间标记:

     

@XmlRootElement(name =“soap:Envelope”,namespace =“soap”)

     

但它只是将该行转换为此

你离你所需要的一步......

soap名称空间http://schemas.xmlsoap.org/soap/envelope/不是soap所以...如果会是这样的话呢?

@XmlRootElement(name = "soap:Envelope", namespace = "http://schemas.xmlsoap.org/soap/envelope/")

顺便说一句。但是你真的需要手动创建SOAP信封吗?实际上标准包javax.xml.soap有一切可以与SOAP一起使用,你可以把你的“其他东西”包装成SOAP信封而不关心你自己构建它吗?

<强>更新: 我强烈建议在使用SOAP Web服务(如Apache CXF等)时使用常规框架,而不是在较低级别上操作SOAP。

但可以使用标准JDK类完成。 示例代码:

package com.foo.tests;

import java.io.ByteArrayOutputStream;
import java.util.Calendar;
import java.util.UUID;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPMessage;

import org.w3c.dom.Document;

public class TestSOAPMessage {

    static MessageFactory factory;
    static DocumentBuilderFactory documentFactory;
    static JAXBContext jaxbCtx;
    static com.foo.tests.pojo.ObjectFactory myStuffFactory = new com.foo.tests.pojo.ObjectFactory();
    static {
        try {
            factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
            documentFactory = DocumentBuilderFactory.newInstance();
            jaxbCtx = JAXBContext.newInstance(com.foo.tests.pojo.MyStuffPojo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String... args) {
        try {
            // prepare test MyStuff JAXB POJO
            com.foo.tests.pojo.MyStuffPojo myStuff = myStuffFactory.createMyStuffPojo();
            // populate myStuff Pojo
            myStuff.setMyPropertyA("property A");
            myStuff.setTimestamp(Calendar.getInstance());
            myStuff.setMessageId(UUID.randomUUID().toString());
            //---
            // marshal JAXB Pojo to DOM Document
            Document myStuffDoc = documentFactory.newDocumentBuilder().newDocument();

            //*** myStuff has @XmlRootElement annotation
             jaxbCtx.createMarshaller().marshal(myStuff, myStuffDoc);

            //*** myStuff does not have @XmlRootElement annotation wrap it and use JAXBElement instead
//          JAXBElement<com.foo.tests.pojo.MyStuffPojo myStuff> jaxbWrapper = myStuffFactory.createMyStuffPojo(myStuff);
//          jaxbCtx.createMarshaller().marshal(jaxbWrapper, myStuffDoc);

            //marshal JAXB Pojo to DOM Document 
            Document myStuffDoc = documentFactory.newDocumentBuilder().newDocument();
            jaxbCtx.createMarshaller().marshal(jaxbWrapper, myStuffDoc);
            //Create SOAPMessage
            SOAPMessage myMessage = factory.createMessage();
            //Optional if we'd like to set those properties...
            myMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
            myMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "utf-8");
            // set myStuff into SOAPBody
            myMessage.getSOAPBody().addDocument(myStuffDoc);        
            //All done. Save changes
            myMessage.saveChanges();

            // Just for test: print message
            ByteArrayOutputStream finalBos = new ByteArrayOutputStream();
            myMessage.writeTo(finalBos);
            System.out.println("my Message: \r\n" + new String(finalBos.toByteArray()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

如何在java bean中添加namespace属性?或

JAXB还提供@XMLSchema注释,我们可以使用它来生成命名空间。

您可以执行以下操作。

 @javax.xml.bind.annotation.XmlSchema(namespace="http://www.springframework.org/schema/beans" , elementFormDefault=javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
    xmlns={     @javax.xml.bind.annotation.XmlNs(namespaceURI="http://www.w3.org/2001/XMLSchema-instance", prefix="xsi"),
    @javax.xml.bind.annotation.XmlNs(namespaceURI="http://schemas.xmlsoap.org/soap/envelope/", prefix="soap")
    }
)

还可以查看this

相关问题