2010-07-12 87 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>