2011-07-27 21 views
3

我有以下XML文件使用LXML

<xml> 
    <network id="5"> 
    <nodelist> 
     <IP>10.10.0.135::3111</IP> 
     <IP>10.10.0.130::3111</IP> 
     <IP>10.10.0.129::3111</IP> 
     <IP>10.10.0.129::3111</IP> 
    </nodelist> 
    <nodelist2/> 
    </network> 
</xml> 

我想刪除所有與IP 10.10.0.129,其中網絡ID = 5的元素刪除文本元素。我怎樣才能在lxml中做到這一點?

目前,我試圖找到使用xpath的節點,我試圖將其刪除。

但是,

netid=xml.xpath("network[@id=%s]/nodelist/IP[contains(text(),%s)]"%(id,node)) 

給我的錯誤lxml.etree.XPathEvalError: Invalid expression

+0

我假設,因爲lxml的主頁說你使用python「的LXML XML工具包是一個Python化結合的C庫libxml2和的libxslt。」 –

+0

我通常不會發布兩個答案,但在這種情況下,一個給你整個xml沒有特定的元素,另一個只給出想要的ip元素。 –

回答

5

我是一名python程序員,所以我讓它在python 2.7中編碼。如果你需要使用不同的語言,你將不得不自己移植它,因爲我除了Python以外什麼都不做。

請注意,雖然這看似處理XPath,我的大部分處理是用python完成的。

import lxml.etree as etree #import etree, like c's include 

def delete(xml,networkid,ipaddr): 
    tree = etree.fromstring(xml) 
    networks = tree.findall('.//network[@id="%s"]'%str(networkid)) #I think you forgot the quotes in your insertion. 
    for network in networks: #for each network that has id='5'. 
     ips = network.findall('.//IP') #All the IP elements under the network 
     for ip in ips: #iterating through a list of ips 
      if ipaddr in ip.text: #if ipaddr is inside the text, even if a port is appended 
       ip.getparent().remove(ip) #the ip's parent (nodelist) removes the ip element 
return tree # I give you the tree 


s = r'''<xml> #Here's your original xml 
    <network id="5"> 
    <nodelist> 
     <IP>10.10.0.135::3111</IP> 
     <IP>10.10.0.130::3111</IP> 
     <IP>10.10.0.129::3111</IP> 
     <IP>10.10.0.129::3111</IP> 
    </nodelist> 
    <nodelist2/> 
    </network> 
</xml>''' 

res = delete(s,'5','10.10.0.129') #here's the result 
print res #and it's a tree. 
print list(res.iter()) #so I print all the items under it. 
print etree.tostring(res) #and you have your edited xml. 
+0

希望我幫了忙。注意:這是用Python 2.7.1運行的lxml(2.3我相信) –

0

這應該是它。

tree.xpath(r'''network[@id="%s"]/nodelist/IP[not(contains(text(),"%s"))]'''%('5','10.10.0.129')) 

其中三個單引號之間的東西是你的XPath代碼(我用Python測試,所以我必須)。這爲您提供了所有符合您要求的IP元素。顯然python的lxml.etree.xml.xpath不會讓我刪除,但這會給你一切。

+0

「tree」是我的名字,用於xml對象 –

0

Python2.7下使用LXML:

tree = ET.fromstring(xml_fragment) ## Or tree = ET.parse(somefile) 

for rn in tree.xpath('network[@id="5"]//IP[starts-with(text(),"10.10.0.129:")]'): 
    rn.getparent().remove(rn)