Удаление тега lxml – неожиданный результат при использовании удаления lxml [дубликат] ⇐ Python
Удаление тега lxml – неожиданный результат при использовании удаления lxml [дубликат]
I have a XML and need to remove a few types of tags. I used the iter method to check each element. I noticed if there is a nested element its child is also deleted. The following tag will not be deleted. For example as follows, the tag delete2 is a child of delete1 and both will be removed. The tag section can't be deleted for some reason. Is this a bug? Or did I miss something? Thanks.
# %% from lxml import etree # unexpected output when nested elements are deleted xml_str = """ """ root = etree.fromstring(xml_str) for element in root.iter(): is_remove = False if element.tag == "delete1": is_remove = True if element.tag == "delete2": is_remove = True if element.tag == "section" and element.attrib.get("name") == "delete": is_remove = True print(f"{element} {is_remove}") if is_remove: element.getparent().remove(element) print(etree.tostring(root, encoding="utf-8").decode("utf-8")) the unexpected output is : False False False True True
Источник: https://stackoverflow.com/questions/780 ... xml-remove
I have a XML and need to remove a few types of tags. I used the iter method to check each element. I noticed if there is a nested element its child is also deleted. The following tag will not be deleted. For example as follows, the tag delete2 is a child of delete1 and both will be removed. The tag section can't be deleted for some reason. Is this a bug? Or did I miss something? Thanks.
# %% from lxml import etree # unexpected output when nested elements are deleted xml_str = """ """ root = etree.fromstring(xml_str) for element in root.iter(): is_remove = False if element.tag == "delete1": is_remove = True if element.tag == "delete2": is_remove = True if element.tag == "section" and element.attrib.get("name") == "delete": is_remove = True print(f"{element} {is_remove}") if is_remove: element.getparent().remove(element) print(etree.tostring(root, encoding="utf-8").decode("utf-8")) the unexpected output is : False False False True True
Источник: https://stackoverflow.com/questions/780 ... xml-remove
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Python lxml.html SyntaxError: неверный предикат с XPath при использовании LXML
Anonymous » » в форуме Python - 0 Ответы
- 23 Просмотры
-
Последнее сообщение Anonymous
-