想使用python elementtree删除XML中具有相同标签名称的多个标签吗?

时间:2013-06-20 14:06:19

标签: python xml elementtree

我是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 :: 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 Shah

1 个答案:

答案 0 :(得分:0)

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

而不是:

root.remove(tag_name)

你应该:

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