我正在尝试读取我所有的 QLineEdit 字段和复选框状态,并使用 Minidom 将它们保存到 XML 文件中。以下是我到目前为止所拥有的。我可以使用 for 循环编写此代码的最简单和最短的方法是什么?
from xml.dom.minidom import Document
# Get all lineEdit values
mac = str(self.lineEdit_mac.text())
broadcast = str(self.lineEdit_broadcast.text())
destination = str(self.lineEdit_destination.text())
port = str(self.lineEdit_port.text())
destinationCheckBox=str(self.checkBox_destination.checkState())
portCheckBox=str(self.checkBox_port.checkState())
# Create the minidom document
doc = Document()
# Create the <wol> base element
wol = doc.createElement("wol")
doc.appendChild(wol)
# Create the <mac> node
node = doc.createElement("mac")
wol.appendChild(node)
# Give the <mac> element some text
nodeText = doc.createTextNode(mac)
node.appendChild(nodeText)
# Create the <broadcast> node
node = doc.createElement("broadcast")
wol.appendChild(node)
# Give the <broadcast> element some text
nodeText = doc.createTextNode(broadcast)
node.appendChild(nodeText)
# Create the <broadcast> node
node = doc.createElement("destination")
wol.appendChild(node)
# Give the <broadcast> element some text
nodeText = doc.createTextNode(destination)
node.appendChild(nodeText)
# Create the <port> node
node = doc.createElement("port")
wol.appendChild(node)
# Give the <port> element some text
nodeText = doc.createTextNode(port)
node.appendChild(nodeText)
# Create the <port> node
node = doc.createElement("destinationCheckBox")
wol.appendChild(node)
# Give the <port> element some text
nodeText = doc.createTextNode(destinationCheckBox)
node.appendChild(nodeText)
# Create the <port> node
node = doc.createElement("portCheckBox")
wol.appendChild(node)
# Give the <port> element some text
nodeText = doc.createTextNode(portCheckBox)
node.appendChild(nodeText)
# Write to document
f = open(fileName, 'w')
doc.writexml(f, indent='',addindent=' ',newl='\n')
f.closed
XML 输出:
<?xml version="1.0" ?>
<wol>
<mac>
00:00:00:00:00:00
</mac>
<broadcast>
192.168.1.255
</broadcast>
<destination>
</destination>
<port>
9
</port>
<destinationCheckBox>
0
</destinationCheckBox>
<portCheckBox>
0
</portCheckBox>
</wol>
另外,将xml格式化为这样的最简单方法是什么?
<?xml version="1.0" ?>
<wol>
<mac>00:00:00:00:00:00</mac>
<broadcast>192.168.1.255</broadcast>
<destination></destination>
<port>9</port>
<destinationCheckBox>0</destinationCheckBox>
<portCheckBox>0</portCheckBox>
</wol>