Get all text from an XML document?

前端 未结 5 1257
闹比i
闹比i 2020-12-11 07:17

How can I get all the text content of an XML document, as a single string - like this Ruby/hpricot example but using Python.

I\'d like to replace XML tags with a sin

5条回答
  •  爱一瞬间的悲伤
    2020-12-11 07:34

    EDIT: This is an answer posted when I thought one-space indentation is normal, and as the comments mention it's not a good answer. Check out the others for some better solutions. This is left here solely for archival reasons, do not follow it!

    You asked for lxml:

    reslist = list(root.iter())
    result = ' '.join([element.text for element in reslist]) 
    

    Or:

    result = ''
    for element in root.iter():
        result += element.text + ' '
    result = result[:-1] # Remove trailing space
    

提交回复
热议问题