0

我是 Python 新手,根据项目要求,我想针对不同的测试用例启动 Web 请求。假设(请参阅下面的 Employee_req.xml)对于一个测试用例,我想与所有组织一起启动 Web 服务。但对于另一个我想启动 Web 服务,其中所有名字标签都应该被删除。我在 python 中使用 ElementTree 来处理 XML。请在下面找到代码段。标签和属性值的修改可以正常工作,没有任何问题。但是在删除某些标签时,它会引发错误。我对 Xpath 不正确,所以你能建议可能的方法吗?

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:: 测试.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

谢谢,

普里扬克·沙阿

4

1 回答 1

0

remove将元素作为参数,而不是 xpath。

代替:

root.remove(tag_name)

你应该有:

elements = root.findall(tag_name)
for element in elements:
    root.remove(element)  
于 2013-06-20T14:31:31.987 回答