2013-06-20 57 views
0

我是Python新手,根據項目要求,我想爲不同的測試用例啓動Web請求。可以說(請參閱下面的Employee_req.xml)我想與所有組織一起啓動Web服務的測試用例。但另一個我想推出的Web服務,其中所有的名字標籤應該被刪除。我在python中使用ElementTree處理XML。請在下面的代碼段找到。標籤和屬性值的修改工作正常,沒有任何問題。但是在移除某些標籤時它會拋出錯誤。我對Xpath不正確,所以你會建議可行的方法嗎?想要使用python elementtree在XML中刪除具有相同標記名稱的多個標記嗎?

Emp_req.xml

<request> 
    <orgaqnization> 
     <name>org1</name> 
     <employee> 
      <first-name>abc</first-name> 
      <last-name>def</last-name> 
      <dob>19870909</dob> 
     </employee> 
    </orgaqnization> 
    <orgaqnization> 
     <name>org2</name> 
     <employee> 
      <first-name>abc2</first-name> 
      <last-name>def2</last-name> 
      <dob>19870909</dob> 
     </employee> 
    </orgaqnization> 
    <orgaqnization> 
     <name>org3</name> 
     <employee> 
      <first-name>abc3</first-name> 
      <last-name>def3</last-name> 
      <dob>19870909</dob> 
     </employee> 
    </orgaqnization> 
</request> 

的Python :: Test.py

modify_query("Remove",tag_name=".//first-name") 
import xml.etree.ElementTree as query_xml 
def modifiy_query(self,*args,**kwargs): 
     root = query_tree.getroot()   
     operation_type=args[0] 
     tag_name=kwargs['tagname'] 
     try:    
      if operation_type=="Remove":  
       logger.info("Removing %s Tag from XML" % tag_name) 
       root.remove(tag_name)    
      elif operation_type=="Insert":       
       logger.info("Inserting %s tag to xml" % tag_name) 
      else: 
       raise InvalidXMLOperationError("Operation " + operation_type + " is invalid") 
     except InvalidXMLOperationError,e: 
      logger.error("Invalid XML operation %s" % operation_type) 

The error message (Flow could be differ because i am running this code from some other program): 

    File "Test.py", line 161, in <module> testsuite.scheduler() 
    File "Test.py", line 91, in scheduler self.launched_query_with("Without_date_range") 
    File "Test.py", line 55, in launched_query_with test.modifiy_query("Remove",tagname='.//first-name') 
    File "/home/XXX/YYYY/common.py", line 287, in modifiy_query parent.remove(child) 
    File "/usr/local/lib/python2.7/xml/etree/ElementTree.py", line 337, in remove self._children.remove(element) 
    ValueError: list.remove(x): x not in list 

謝謝,

Priyank沙

+0

你能提供的錯誤信息? –

+0

它是ValueError:ValueError:list.remove(x):x不在列表中 –

+1

如果您在問題中粘貼了整條消息,會更容易。 –

回答

0

remove需要一個元素作爲參數,而不是一個的xpath。

相反的:

root.remove(tag_name) 

你應該有:

elements = root.findall(tag_name) 
for element in elements: 
    root.remove(element) 
+0

這仍然不起作用。下面是我做的代碼:我調用這個函數,如:: Test.modifiy_query(「Remove」,tagname ='first-name')'tag_name = kwargs ['tagname'] logger.info(「Removing%s從XML標記」%TAG_NAME) 的childNodes = root.findall(TAG_NAME) 打印LEN(的childNodes) 對孩子的childNodes: root.remove(子)' –

+0

感謝morphyn ..我通過調整邏輯解決此問題:感謝您的時間...'tag_name = kwargs ['tagname'] logger.info(「從XML刪除%s標記」%tag_name) parentlist = root.findall(「.//*」) 父列表中的父項:如果孩子不是無 parent.remove(child)' –

相關問題