如何使用go-libxml2更新特定的XML元素值

Ach*_*ius 8 xml go libxml2

我想使用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>
Run Code Online (Sandbox Code Playgroud)

我想在所有值中添加其他查询参数。所以我的结果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>
Run Code Online (Sandbox Code Playgroud)

如何使用go-libxml2修改XML?

use*_*422 2

如何使用go-libxml2修改XML?

你不能。go-libxml2 可以加载 XML 格式的文本并使用节点,但它没有序列化为 XML 格式的文本的功能。

或者您需要编写自己的函数来将节点树转换为 XML 格式的字符串。

话虽这么说,您可以按如下方式加载和修改 url:

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.
Run Code Online (Sandbox Code Playgroud)