Python 2.6.1 : expected path separator ([)

折月煮酒 提交于 2019-12-05 13:54:32

问题


I am getting a path separator error in python 2.6.1. I have not found this issue with python 2.7.2 version, but unfortunately I need this in 2.6.1 only. Is there any another way to achieve the same? :(

my code :-

import xml.etree.ElementTree as ET #version 1.2.6
import sys   

class usersDetail(object): 

    def __init__(self, users=None):
        self.doc = ET.parse("test.xml")
        self.root = self.doc.getroot()

    def final_xml(self,username):
        r = self.root.find("user[@username='user1']") #not working in 2.6.1 :(
        self.root.remove(r)
        print r
        tree = ET.ElementTree(self.root)
        tree.write("msl.xml") 

if __name__ == '__main__':
    parser = usersDetail()
    parser.final_xml("user1") 

test.xml is :-

<?xml version="1.0"?>
<users>
<user afp="yes" cifs="yes"  username="user1" volume="vol" webdev="yes" /></user>
</users>

What this will do is it will remove the xml only if username = username. Thanks in advance for your valuable time.


回答1:


You are using an XPath expression, that is not supported by the ElementTree version included in Python 2.6. You'll need to filter for the attribute manually, after a .findall():

def final_xml(self,username):
    users = self.root.findall("user")
    for user in users:
        if user.attrib.get('username') == 'user1':
            break
    else:
        raise ValueError('No such user')

    # `user` is now set to the correct element
    self.root.remove(user)
    print user
    tree = ET.ElementTree(self.root)
    tree.write("msl.xml") 


来源:https://stackoverflow.com/questions/13667979/python-2-6-1-expected-path-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!