我想使用go-libxml2更新XML元素值。该元素可以出现在XML文档中的任何位置。例如,在下面的XML中,我想更新一个元素
<?xml version="1.0" encoding="UTF-8"?>
- <note>
<to>Tove</to>
<from>Jani</Ffrom>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<url>http://example.com</url>
<links>
<url>http://link1.com</url>
<url>http://link2.com</url>
</links>
</note>
我想在所有值中添加其他查询参数。因此,我生成的xml将如下所示
<?xml version="1.0" encoding="UTF-8"?>
- <note>
<to>Tove</to>
<from>Jani</Ffrom>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<url>http://example.com?param=value</url>
<links>
<url>http://link1.com?param=value</url>
<url>http://link2.com?param=value</url>
</links>
</note>
如何使用go-libxml2修改XML?
如何使用go-libxml2修改XML?
您不能。 go-libxml2可以加载XML格式的文本并可以与节点一起使用,但是它不具有序列化为XML格式的文本的功能。
或者您需要编写自己的函数,以将节点树转换为XML格式的字符串。
话虽如此,您可以按如下方式加载和修改网址:
doc, err := libxml2.ParseString(xmlstring)
nodes := xpath.NodeList(doc.Find(`//url`))
for i := 0; i < len(nodes); i++ {
newvalue := nodes[i].NodeValue() + "?param=value"
nodes[i].SetNodeValue(newvalue)
}
// But here you cannot serialize back the 'doc' tree to XML with go-libxml2.
// You need to code on your own.