python 解释xml

python 解释xml

模块:xml.etree.Element

    1.字符解释
    2.文件解释

主要方法:

    1.parse('xxx.xml')      #解释xml,返回xml文件对像
    2.getiterator('要找的节点名') #获取所有要找的指定节点
    3.getchildren   #获取子节点
    4.find          #查找节点
    5.findall       #查找所有要找的指定节点
  6.set      #设置节点属性 7.write #保存到文件
<breakfast_menu>
<food>
<name>haha</name>
<price>$5.95</price>
<description>
two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
light Belgian waffles covered with an assortment of fresh berries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
two eggs, bacon or sausage, toast, and our ever-popular hash browns
</description>
<calories>950</calories>
</food>
</breakfast_menu>
View Code

 

 
from xml.etree import ElementTree as et

fobj = et.parse('data\\test.xml')
#fobj = et.parse(open('test.xml').read())
root = fobj.getroot()

#查找food,返回list
t = fobj.getiterator('food')

#查找food下面的name
#node = fobj.find('food/name')
#print node.tag, node.text

#查找所有food下面的name
node = fobj.findall('food/name')
for n in node:
    print n.tag, n.text

for p in t:
    #获取字节点
    children = p.getchildren()
    for chd in children:
        if chd.tag == 'name' and chd.text == 'Belgian Waffles':
            #chd.text = 'haha'
            print chd.text
    print '================='

#修改后重新保存
fobj.write('data\\test.xml')
View Code

 

 
posted @ 2017-11-26 14:10  hrwu  阅读(129)  评论(0)    收藏  举报