python xml生成 python 生成xml

2021-10-13 10:36:57 字數 1794 閱讀 2385

用到這個模組的時候,感覺網上大部分資料比較繁瑣,所以自己寫了個簡單的def

其實最主要掌握以下幾個函式

1.doc=xml.dom.minidom.document()#生成xml的dom樹物件

2.root=doc.createelement("root")#建立樹節點,可以使根節點或者是子節點

3.child.setattribute('value',value)#設定節點屬性

示例如下:

def writexml(servername,ip,port,provider,description,value):

try:

fp=open("c:\\users\***\desktop\python3.6.2\網域名稱解析\***.xml","w",encoding="utf-8")

try:

doc=xml.dom.minidom.document()

root=doc.createelement("root")

child1=doc.createelement("server")

child1.setattribute('name',servername)

child_error=doc.createelement("error")

child_error.setattribute('description', description)

child_error.setattribute('value',value)

child2=doc.createelement("address")

child3=doc.createelement('addr')

child3.setattribute('ip',ip[0])

child3.setattribute('port', port[0])

child3.setattribute('provider', provider[0])

child4=doc.createelement('addr')

child4.setattribute('ip', ip[1])

child4.setattribute('port', port[1])

child4.setattribute('provider', provider[1])

child5 = doc.createelement('addr')

child5.setattribute('ip', ip[2])

child5.setattribute('port', port[2])

child5.setattribute('provider', provider[2])

doc.writexml(fp,indent='\t', addindent='\t', newl='\n', encoding="utf-8")

except :

traceback.print_exc()

logging.warning("writexml allerror%s"%traceback.print_exc())

finally:

fp.close()

except oserror as err:

print("os error: ".format(err))

logging.warning('writexml oserror:%s'%err)

except valueerror:

print("could not convert data to an integer.")

logging.warning('writexml valueerror:%s'%valueerror)

python xml解析和生成

解析使用xml.etree.elementtree 模組,生成使用xml.dom.minidom模組,elementtree比dom快,dom生成簡單且會自動格式化。xml version 1.0 encoding utf 8 baspools bas basprovider 0 basprovid...

python xml解析例子

coding utf 8 created on thu apr 16 23 18 27 2015 author shifeng 功能 解析cdr sample.xml檔案,輸出格式為dnorm接收的格式,並將訓練集的 label 寫入到文件中 xml檔案 見csdn資源共享 import codec...

python xml檔案 操作

我的.xml檔案如下 通過如下 模板,可實現對.xml檔案的資訊快捷讀取 導入庫檔案 from xml.etree.elementtree import elementtree,element 指定.xml檔案位址 xml path users megvii desktop retail 001.x...