瞭解就行了** 通過新建file建立含有標簽,標簽屬性##xml的格式如下,就是通過<>節點來區別數據結構的: <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year ...
瞭解就行了**
通過新建file建立
含有標簽,標簽屬性
##xml的格式如下,就是通過<>節點來區別數據結構的:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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>View Code
##python中操作xml:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import xml.etree.ElementTree as ET 2 3 tree = ET.parse("xmltest.xml") 4 root = tree.getroot() 5 print(root.tag) # 最外層的標簽名 6 7 #遍歷xml文檔 8 for child in root: 9 print(child.tag, child.attrib) # tag是標簽,attrib是屬性 10 for i in child: 11 print(i.tag,i.text) 12 13 #只遍歷year 節點 14 for node in root.iter('year'): 15 print(node.tag,node.text) 16 #--------------------------------------- 17 import xml.etree.ElementTree as ET 18 19 tree = ET.parse("xmltest.xml") 20 root = tree.getroot() 21 22 #修改 23 for node in root.iter('year'): 24 new_year = int(node.text) + 1 25 node.text = str(new_year) 26 node.set("updated","yes") 27 28 tree.write("xmltest.xml") 29 30 31 #刪除node 32 for country in root.findall('country'): 33 rank = int(country.find('rank').text) 34 if rank > 50: 35 root.remove(country) 36 37 tree.write('output.xml')View Code