Home > OS >  Golang XML etree: Unexpected <></> when adding outer layer
Golang XML etree: Unexpected <></> when adding outer layer

Time:10-05

I tried to add outer XML to my XML using golang library that is called https://github.com/beevik/etree assume my XML is <Foo></Foo> but when trying to add the outer layer there's an additional empty tag like <></> how to remove that?

Here's my snippet: https://go.dev/play/p/z6E5Ha3hWmm

and the result is

<soap:Envelope>
  <soap:Header/>
  <soap:Body/>
  <><Foo/></>
</soap:Envelope>

I expected the result is

<soap:Envelope>
  <soap:Header/>
  <soap:Body/>
  <Foo/>
</soap:Envelope>

There's <></> between

EDIT The <Foo/> is dynamic, so it can be <Bar/> or anything else

CodePudding user response:

Turns out, I just need to add .Root() So it should be soapBody.AddChild(result.Root())

https://go.dev/play/p/F84DOOGo0p-

CodePudding user response:

I'm far more familiar with etree than with golang, so you may have to take the following with a grain (or two) of salt (and re-write it), but you need to do a couple of basic xml-related things:

First, you have to wrap your <Foo> element in a root element to make it well formed xml document and then, inside that document, select that element.

Second, in the second (root) document, select the location where you want the <Foo> element to be added and then add it.

So it should look like this:

    result := etree.NewDocument()
    root := etree.NewDocument()

    root.ReadFromString("<soap:Envelope><soap:Header/><soap:Body/></soap:Envelope>")
    result.ReadFromString("<root><Foo/></root>")

    source := result.FindElements("//Foo")[0]
    destination := root.FindElements("//soap:Envelope")[0]

    destination.AddChild(source)

See the updated snippet here.

  • Related