开发者

Changing Element Value in Existing XML File Using DOM

I am trying to find examples of how to change an existing xml files Element Value.

Using the following xml example:

<book>
  <title>My Book</title>
  <aut开发者_StackOverflow中文版hor>John Smith</author>
</book>

If I wanted to replace the author element value 'John Smith' with 'Jim Johnson' in a Python script using DOM, how would I go about doing so? I've tried to look for examples on this, but have failed in doing so. Any help would be greatly appreciated.

Regards, Rylic


Presuming

s = '''
<book>
  <title>My Book</title>
  <author>John Smith</author>
</book>'''

DOM would look like:

from xml.dom import minidom

dom = minidom.parseString(s) # or parse(filename_or_file)
for author in dom.getElementsByTagName('author'):
    author.childNodes = [dom.createTextNode("Jane Smith")]

But I'd encourage you to look into ElementTree, it makes working with XML a breeze:

from xml.etree import ElementTree

et = ElementTree.fromstring(s) # or parse(filename_or_file)
for author in et.findall('author'):
    author.text = "Jane Smith"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜