I want to update a XML element value using go-libxml2. The element may occur anywhere in the XML document. For example in the following XML I want to update a element
<?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>
I want to add a additional query parameters in all values. So my resultant xml will be as follows
<?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>
How to use go-libxml2 to modify XML?
How to use go-libxml2 to modify XML?
You cannot. go-libxml2 can load an XML-formatted text and work with the nodes, but it has no function for serializing to an XML-formatted text.
Or you need to code your own functions for converting the tree of nodes to an XML-formatted string.
That being said, you can load and modify the urls as follows:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With