標籤:-- odi 文檔 操作xml 資料 text name span sub
xml模組
xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單,
不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的介面還主要是xml。
xml的格式如下,就是通過<>節點來區別資料結構的:
<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>
xml協議在各個語言裡的都 是支援的,在python中可以用以下模組操作xml
遍曆
import xml.etree.ElementTree as ETtree = ET.parse("xml test") # 開啟xml檔案root = tree.getroot() # 得到根節點# print(dir(root))print(root.tag)# 遍曆xml文檔for child in root: print(‘----------‘,child.tag, child.attrib) # 列印country節點 for i in child: print(i.tag,i.text)修改和刪除xml文檔內容
import xml.etree.ElementTree as ETtree = ET.parse("xml_test")root = tree.getroot() #f.seek(0)# 修改for node in root.iter(‘year‘): new_year = int(node.text) + 5 node.text = str(new_year) # 修改內容 node.set("attr_test","false")tree.write(‘output.xml‘) # 寫入檔案# #刪除nodefor country in root.findall(‘country‘): rank = int(country.find(‘rank‘).text) if rank > 50: root.remove(country)tree.write(‘output.xml‘)建立xml
import xml.etree.ElementTree as ETroot = ET.Element("namelist") # 建立rootname = ET.SubElement(root,"name",attrib={"enrolled":"yes"}) # 建立child--nameage = ET.SubElement(name,"age",attrib={"checked":"no"}) # 建立name child--age,sex,namesex = ET.SubElement(name,"sex")n = ET.SubElement(name,"name")n.text = "Alex Li"sex.text = ‘male‘name2 = ET.SubElement(root,"name",attrib={"enrolled":"no"})age = ET.SubElement(name2,"age")age.text = ‘19‘et = ET.ElementTree(root) # 產生文檔對象et.write("build_out.xml", encoding="utf-8",xml_declaration=True)
由於原生儲存的XML時預設無縮排,如果想要設定縮排的話, 需要修改儲存方式
import xml.etree.ElementTree as ETfrom xml.dom import minidomdef subElement(root, tag, text): ele = ET.SubElement(root, tag) ele.text = textdef saveXML(root, filename, indent="\t", newl="\n", encoding="utf-8"): rawText = ET.tostring(root) dom = minidom.parseString(rawText) with open(filename, ‘w‘) as f: dom.writexml(f, "", indent, newl, encoding)root = ET.Element("namelist")to = root.makeelement("to", {})to.text = "peter"root.append(to)name = ET.SubElement(root,"name",attrib={"enrolled":"yes"}) # 建立child--nameage = ET.SubElement(name,"age",attrib={"checked":"no"}) # 建立name child--age,sex,namesex = ET.SubElement(name,"sex")n = ET.SubElement(name,"name")n.text = "Alex Li"sex.text = ‘male‘name2 = ET.SubElement(root,"name",attrib={"enrolled":"no"})age = ET.SubElement(name2,"age")age.text = ‘19‘# et = ET.ElementTree(root) # 產生文檔對象# 儲存xml檔案saveXML(root, "note.xml")
Python模組——xml