使用lxm向现有元素添加属性、删除元素等

2024-05-23 17:39:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用

from lxml import etree

tree = etree.parse('test.xml', etree.XMLParser())

现在我想研究解析的XML。我在删除带有名称空间的元素时遇到问题,或者只删除一般的元素,例如

<rdf:description><dc:title>Example</dc:title></rdf:description>

我想删除整个元素以及标签中的所有内容。我还想向现有元素添加属性。我需要的方法在Element类中,但是我不知道如何在这里使用ElementTree对象。任何建议都会非常感谢的,谢谢


Tags: fromtestimporttree元素titleparserdf
2条回答

remove方法应该做您想做的事情:

>>> from lxml import etree
>>> from StringIO import StringIO

>>> s = '<Root><Description><Title>foo</Title></Description></Root>'
>>> tree = etree.parse(StringIO(s))

>>> print(etree.tostring(tree.getroot()))
<Root><Description><Title>foo</Title></Description></Root>

>>> title = tree.find('//Title')
>>> title.getparent().remove(title)
>>> etree.tostring(tree.getroot())
'<Root><Description/></Root>'

>>> print(etree.tostring(tree.getroot()))
<Root><Description/></Root>

您可以通过此调用访问根元素:root=tree.getroot()

使用该根元素,可以使用findall()并删除符合条件的元素:

deleteThese = root.findall("title")
for element in deleteThese: root.remove(element)

最后,您可以看到新树的外观:etree.tostring(root, pretty_print=True)

以下是有关find/findall如何工作的一些信息: http://infohost.nmt.edu/tcc/help/pubs/pylxml/class-ElementTree.html#ElementTree-find

要向元素添加属性,请尝试以下操作:

root.attrib['myNewAttribute']='hello world'

相关问题 更多 >