Child index out of range, python element tree

自作多情 提交于 2019-12-13 02:55:56

问题


I am receiving an error I have never received before when trying to run this code.

File "BasicEmail.py", line 96, in init_ui root[0][1].text IndexError: child index out of range Abort trap: 6

My code is simple,

class EmailBlast(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        user_file = 'user_info.xml'
        tree = ET.parse(user_file)
        root = tree.getroot()
        root[0][1].text
        self.emailLabel = QtWidgets.QLabel("Email:")
        self.emailListLabel = QtWidgets.QLabel("")
        self.sendButton = QtWidgets.QPushButton("Save")
        self.settingsButton = QtWidgets.QPushButton("Settings")

        h_box = QtWidgets.QHBoxLayout()
        h_box.addStretch()

        v_box = QtWidgets.QVBoxLayout()
        v_box.addWidget(self.emailLabel)
        v_box.addWidget(self.emailListLabel)
        v_box.addWidget(self.sendButton)
        v_box.addWidget(self.settingsButton)        
        v_box.addLayout(h_box)

        self.setLayout(v_box)
        self.setWindowTitle("Email Blast")

        self.settingsButton.clicked.connect(lambda: self.settings(self.settingsButton, "Saved"))        
        self.show()

    def settings(self, settingsButton, string):
        self.ui = ConfigWindow()
        self.hide()        
        print("Settings")

I am able to get the tags and attributes, no values. The data in the XML is fine and there should be an array, or list, there for me to pull from.

Included full xml file:

<data>
<email>ewokhugz@gmail.com</email>
<password>testpass</password>
<smtp>gmail</smtp>
<port>587</port>
</data>`

回答1:


Your data xml pattern presents the children directly inside the root, so no need to access a nested child:

root = tree.getroot()
root[0].text # returns the email
root[1].text # returns the password
root[2].text # returns the smtp 
root[3].text # returns the port

You can also use the name query to allow some change in your pattern :

root.find('email').text 


来源:https://stackoverflow.com/questions/45575455/child-index-out-of-range-python-element-tree

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