How can one replace an element with text in lxml?

前端 未结 3 2106
礼貌的吻别
礼貌的吻别 2020-12-16 16:32

It\'s easy to completely remove a given element from an XML document with lxml\'s implementation of the ElementTree API, but I can\'t see an easy way of consistently replaci

3条回答
  •  渐次进展
    2020-12-16 16:39

    Using ET.XSLT:

    import io
    import lxml.etree as ET
    
    data = '''
    Some text before 
     and some text after.
    
    Text before  and after
     Text after a sibling  Text before a sibling
    
    '''
    
    f=ET.fromstring(data)
    xslt='''\
            
    
        
        DELETED
    
            
        
            
                
            
        
        
            
        
        
    '''
    
    xslt_doc=ET.parse(io.BytesIO(xslt))
    transform=ET.XSLT(xslt_doc)
    f=transform(f)
    
    print(ET.tostring(f))
    

    yields

    
    Some text before DELETED
    DELETED and some text after.
    DELETED
    Text before DELETED and after
     Text after a sibling DELETED Text before a sibling
    
    

提交回复
热议问题