find xml element based on its attribute and change its value

后端 未结 4 988
清歌不尽
清歌不尽 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条回答
  •  花落未央
    2021-02-01 09:30

    You can access the attribute value as this:

    from elementtree.ElementTree import XML, SubElement, Element, tostring
    
    text = """
    
        
            
            
            
        
    
        
            
            
        
    
    """
    
    elem = XML(text)
    for node in elem.find('phoneNumbers'):
        print node.attrib['topic']
        # Create sub elements
        if node.attrib['topic']=="sys/phoneNumber/1":
            tag = SubElement(node,'TagName')
            tag.attrib['attr'] = 'AttribValue'
    
    print tostring(elem)
    

    forget to say, if your ElementTree version is greater than 1.3, you can use XPath:

    elem.find('.//number[@topic="sys/phoneNumber/1"]')
    

    http://effbot.org/zone/element-xpath.htm

    or you can use this simple one:

    for node in elem.findall('.//number'):
        if node.attrib['topic']=="sys/phoneNumber/1":
            tag = SubElement(node,'TagName')
            tag.attrib['attr'] = 'AttribValue'
    

提交回复
热议问题