2010-07-12 226 views
5

删除元素,等我在XML使用添加属性现有元素,LXML

from lxml import etree 

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

现在我想在解析的XML解析工作。我在使用的命名空间的麻烦删除元素或一般如

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

,我想删除标签内的所有元素以及一切只是元素。我也想为现有元素添加属性。我需要的方法是在Element类中,但我不知道如何在此处使用ElementTree对象。任何指针将肯定会感激,谢谢

回答

14

您可以通过此调用正本清源元素:root=tree.getroot()

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

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

最后,你可以看到你的新树会变成什么样子的:etree.tostring(root, pretty_print=True)

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

将属性添加到一个元素,尝试这样的事情:

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

如何我会发现时髦的标签的任何想法,例如作为? – axsuul 2010-07-12 22:40:26

+0

@axsuul你有没有想过如何添加时髦的标签? – 2016-06-09 00:23:41

+0

@ShreedharManek对不起,这个项目已经很久了。我不记得了! – axsuul 2016-06-10 01:23:15

1

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>