python处理xml文件
# pip install pyyaml 环境里先安装包
import xml.dom.minidom dom = xml.dom.minidom.parse('config.xml') root = dom.documentElement def xml(suser): suser = root.getElementsByTagName(suser) return suser[0].firstChild.data id = xml('id') # 进程名 print("打印ID:"+id) import xml.etree.ElementTree as ET # 从文件加载并解析 XML 数据 tree = ET.parse('country_data.xml') root = tree.getroot() print(root.tag) # 打印根节点名称 print(root.attrib) # 打印根节点属性 # for 循环可以列出所有的子节点: # 子节点与属性 for child in root: print(child.tag, child.attrib) #使用索引的方式存取任意的节点 print(root[0][1].text) #get 直接取得指定的属性值 print(root[0][3].get('name')) #iter 可以在指定节点之下,以递回方式搜索所有子节点: for neighbor in root.iter('neighbor'): print(neighbor.attrib) # find 则是只从第一层子节点中搜索(不包含第二层以下),findall 会传回所有结果,而 find 则是只传回第一个找到的节点: # 只从第一层子节点中搜索,传回所有找到的节点 for country in root.findall('country'): # 只从第一层子节点中搜索,传回第一个找到的节点 rank = country.find('rank').text # 取得节点指定属性质 name = country.get('name')
附录:
config.xml
<config>
<id>905594711349653</id>
<sec>0tn1jeerioj4x6lcugdd8xmzvm6w42tp</sec>
</config>
country_data.xml
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
浙公网安备 33010602011771号