python 解析xml有好几中方式,这里主要使用了xml.dom.minidom和xml.etree.ElementTree, 通过使用感受来看,使用ElementTree的方式更加简单且高效,以下是代码段,主要涉及获取和修改,后续增加写入部分
from xml.dom.minidom import parse, parseString
import xml.etree.ElementTree as ET
def parseXmlByET():
tree=ET.parse("./server.xml") #打开xml文件 好像可以直接ET.parse(xml_file_path)
root = tree.getroot() #获取根节点
for currServer in root.iter("CurrServer") :
print(currServer.text)
if currServer.text == "foreign" :
currServer.text = "cn"
else :
currServer.text = "foreign"
for version in root.iter("Version") :
print(version.text)
if version.text== "2" :
version.text = "1"
else :
version.text = "2"
for Server in root.iter("Server") :
name = Server.get("name")
url = Server.get("url")
print (name)
print (url)
if name == "cn" :
Server.set("url", "https://192.168.1.1:80")
else :
Server.set("url", "https://192.168.1.1:443")
tree.write("./server.xml", encoding="utf-8", xml_declaration=True)
def parseXmlByMiniDom():
dom = parse("./server.xml")
root = dom.documentElement
print(root.nodeName)
CurrServerNode = root.getElementsByTagName("CurrServer")[0]
# print(CurrServerNode.nodeName)
# print (CurrServerNode.childNodes[0].data)
if CurrServerNode.childNodes[0].data == "foreign" :
CurrServerNode.childNodes[0].data = "cn"
else :
CurrServerNode.childNodes[0].data = "foreign"
Versions = root.getElementsByTagName("Version");
for Version in Versions :
print(Version.nodeName)
if Version.childNodes[0].data == "2" :
Version.childNodes[0].data = "1"
else :
Version.childNodes[0].data = "2"
Servers = root.getElementsByTagName("Server");
for Server in Servers :
print (Server.nodeName)
name = Server.getAttribute("name")
url = Server.getAttribute("url")
print(name)
print(url)
if (name == "foreign") :
Server.setAttribute("url", "https://172.23.0.1:443")
else :
Server.setAttribute("url", "https://172.23.0.1:80")
f = open("./Server.xml", "w")
rootxml = root.toxml(encoding="UTF-8")
f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
f.write(rootxml.decode())
def main() :
print ("hello world!")
#parseXmlByMiniDom()
parseXmlByET()
if __name__ == '__main__':
main()