我想使用 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?
最佳答案
How to use go-libxml2 to modify 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.
关于xml - 如何使用 go-libxml2 更新特定 XML 元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57986772/