问题
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