英文:
Golang XML etree: Unexpected <></> when adding outer layer
问题
我尝试使用名为https://github.com/beevik/etree的golang库向我的XML中添加外部XML。假设我的XML是<Foo></Foo>
,但是当尝试添加外层时,会出现一个额外的空标签,如<></>
。如何移除它?
这是我的代码片段:
https://go.dev/play/p/z6E5Ha3hWmm
结果是:
<soap:Envelope>
<soap:Header/>
<soap:Body/>
<><Foo/></>
</soap:Envelope>
我期望的结果是:
<soap:Envelope>
<soap:Header/>
<soap:Body/>
<Foo/>
</soap:Envelope>
在<Foo/>
之间有<></>
。
编辑
<Foo/>
是动态的,所以它可以是<Bar/>
或其他任何内容。
英文:
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 <Foo/>
EDIT
The <Foo/>
is dynamic, so it can be <Bar/>
or anything else
答案1
得分: 1
原文:Turns out, I just need to add .Root()
So it should be soapBody.AddChild(result.Root())
翻译结果:原来如此,我只需要添加.Root()
。
所以应该是soapBody.AddChild(result.Root())
。
英文:
Turns out, I just need to add .Root()
So it should be soapBody.AddChild(result.Root())
答案2
得分: 0
我对etree比对golang更熟悉,所以你可能需要对以下内容持保留态度(并重新编写),但你需要完成一些基本的与xml相关的操作:
首先,你需要将<Foo>
元素包装在一个根元素中,以使其成为一个格式良好的xml文档,然后在该文档中选择该元素。
其次,在第二个(root
)文档中,选择要添加<Foo>
元素的位置,然后将其添加进去。
代码应该如下所示:
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论