Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update specific XML element value using go-libxml2

Tags:

xml

go

libxml2

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?

like image 832
Achaius Avatar asked Sep 18 '19 06:09

Achaius


Video Answer


1 Answers

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.
like image 96
user803422 Avatar answered Oct 20 '22 03:10

user803422