Skip to content

Question: Best practice/way to serialize an object #9

@minhderien

Description

@minhderien

I'm tring to serialize an object to look like the following and seeking for the best practice:

<Soap-ENV:Envelope xmlns:Soap-Env="someEnvelopeUri">
    <Soap-ENV:Header xmlns:header="someHeaderUri">
        <header:name>Name</header:name>
    </Soap-ENV:Header>
    <Soap-ENV:Body>
        <ADynamicRequest>
            <service>SomeService</service>
        </ADynamicRequest>
    </Soap-ENV:Body>
</Soap-ENV:Envelope>

Hence my object would look like the following:

import { XMLDecoratorSerializer } from "xmldom-decorators";
import { XMLElement, XMLRoot } from "xmldom-decorators/lib/decorators";

export class Header {
    @XMLElement({ types: [{ name: 'name', namespaceUri: 'someHeaderUri'}]})
    name: string;
}

export class ADynamicRequest {
    @XMLElement({ types: [{ name: 'service'}]})
    service: string;
}

@XMLRoot({ name: 'Envelope', namespaceUri: 'someEnvelopeUri'})
export class SoapEnvelope {
    @XMLElement({ types: [{name: 'Header', namespaceUri: 'someEnvelopeUri'}]})
    header: Header;

    @XMLElement({ types: [{ name: 'Body', namespaceUri: 'someEnvelopeUri'}]})
    //@XMLArray({ name: 'Body', namespaceUri: 'someEnvelopeUri'})
    soapBody: any; // [any], [BodyWrapperClass] type maybe?
    // Works well when the Specific type is given like ADynamicRequest type , but I'm tring to make it more generic so we can serialize any type of Object
    // For example, the type for the body could be a GetDataRequest or GetWeatherRequest

    public static GenerateEnvelope(): string {
        const header: Header = {
            name : 'Name'
        }
        const body : ADynamicRequest = {
            service: 'SomeService'
        }


        const soapEnvelope: SoapEnvelope = {
            header: header,
            soapBody: body
        }

        let serializer = new XMLDecoratorSerializer();
        let serializedObject: string = 
            serializer.serialize(
                soapEnvelope,
                SoapEnvelope,
                {
                    'someEnvelopeUri': 'Soap-ENV',
                    'someHeaderUri': 'header',
                }
            )
        console.log(serializedObject)
        return serializedObject;
    }
}



I do not get the expected result. I'm asking for help/guidance on how should I structure this. Should I serialize bits by bit and append them together instead?
Also I notice that the xmlns prefix is not working like I expect.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions