Home > Blockchain >  how to make nested xml with goland by go xml marshal
how to make nested xml with goland by go xml marshal

Time:09-22

i have a soap request that i need to make an xml to make the request . so what i have done to make xml is like below :

type Command struct {
        XMLName xml.Name
    }

    type XMLEnvelop struct {
        XMLName        xml.Name `xml:"soapenv:Envelope"`
        Xmlns          string   `xml:"xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/,"`
        CalculatePrice Command  `xml:"soapenv:Body>FunctionName"`
    }

    v := &XMLEnvelop{Xmlns: "namespace1", CalculatePrice: Command{xml.Name{"namespace2", "CalculatePrice"}}}

    output, err := xml.MarshalIndent(v, "", "    ")
    if err != nil {
        fmt.Printf("error: %v\n", err)
    }

    // Write the output to check
    os.Stdout.Write(output)

this will give me this output :

<soapenv:Envelope>
    <xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/>namespace1</xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/>
    <soapenv:Body>
        <CalculatePrice xmlns="namespace2"></CalculatePrice>
    </soapenv:Body>
</soapenv:Envelope>

now what i want to make some fields inside the calculateprice i could not find it on the net so as example the xml would be like :

        <CalculatePrice xmlns="namespace2">
        <test>somevalue</test>
        <someothertest>somevalue</someothertest>
        </CalculatePrice>

CodePudding user response:

Please Change the struct Command and XMLEnvelop :-

type Command struct {
    Xmlns string `xml:"xmlns,attr"`
    Test string `xml:"test"`
    Someothertest string `xml:"someothertest"`  
} 
type XMLEnvelop struct {
    XMLName        xml.Name `xml:"soapenv:Envelope"`
    Xmlns          string   `xml:"xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/,"`
    CalculatePrice Command  `xml:"soapenv:Body>CalculatePrice"`
}

And change the v := &XMLEnvelop{Xmlns: "namespace1", CalculatePrice: Command{Xmlns: "namespace2",Test: "somevalue", Someothertest: "somevalue"}}

Test In Playground

  • Related