find xml element based on its attribute and change its value

后端 未结 4 1033
清歌不尽
清歌不尽 2021-02-01 08:44

I am using python xmlElementTree and want to assign or modify a xml element value based on its attribute. Can somebody give me an idea how to do this?

For example: Here

4条回答
  •  Happy的楠姐
    2021-02-01 09:29

    I'm not familiar with xmlElementTree, but if you're using something capable of xpath expressions you can locate a node by attribute value using an expression like this:

    //number[@topic="sys/phoneNumber/1"]
    

    So, using the etree module:

    >>> import lxml.etree as etree
    >>> doc = etree.parse('foo.xml')
    >>> nodes = doc.xpath('//number[@topic="sys/phoneNumber/1"]')
    >>> nodes
    []
    >>> etree.tostring(nodes[0])
    '\n    '
    

提交回复
热议问题