How to include the soap envelope tag when marshall

2019-07-23 09:28发布

问题:

I am marshalling a soap request using JAXB. It is working but the resulting XML does not contain the soap:Envelope tag. Also, the namespace is indicated on root element instead of inside the soap:Envelope tag. There is also an additional standalone attribute on the xml tag. How can I achieved an output similar to the 2nd XML below using JAXB's marshaller?

Currently, here's how my marshalled XML looks like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer xmlns:ns="http://www.example.org/beanLevelNamespace">
    <ns:id>201200001</ns:id>
    <ns:name>Name</ns:name>
    <ns:age>18</ns:age>
</Customer>

And here is how I want it to look like:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
    xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
    soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">   
    <soap:Body xmlns:ns="http://www.example.org/beanLevel1Namespace" xmlns:ns1="http://www.example.org/beanLevel2Namespace">
        <ns:Customer>
            <ns1:id>201200001</ns:id>
            <ns1:name>Name</ns:name>
            <ns1:age>18</ns:age>
        </ns:Customer>
    </soap:Body>
</soap:Envelope>

回答1:

You can add your XML inside an Envelope before sending.

"<Envelope><Body>" + your_xml + "</Body></Envelope>

Always keep your namespace at the element level; not at Envelope level. Because you get clarity when looking at an element what type it is. It doesn't matter where you keep the namespace.

There's a problem with your marshalled XML. Correct XML is:

<ns:Customer xmlns:ns="http://www.example.org/beanLevelNamespace">
    <ns:id>201200001</ns:id>
    <ns:name>Name</ns:name>
    <ns:age>18</ns:age>
</ns:Customer>

Again, it doesn't matter where you put the namespace declaration:

<ns:Customer xmlns:ns="http://www.example.org/beanLevelNamespace">
    <ns:id>201200001</ns:id>
</ns:Customer>

<Customer xmlns="http://www.example.org/beanLevelNamespace">
    <id>201200001</id>
</Customer>

<ns1:Customer xmlns:ns1="http://www.example.org/beanLevelNamespace">
    <ns2:id xmlns:ns2="http://www.example.org/beanLevelNamespace">201200001</ns2:id>
</ns1:Customer>

They are all same.