友善交流技术...

python read xml

上一篇 / 下一篇  2012-12-12 13:56:45 / 个人分类:python

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import dump
from xml.etree.ElementTree import Comment
from xml.etree.ElementTree import tostring
from xml.etree.ElementTree import fromstring
from xml.etree import ElementTree

data='''<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder>
   <item ty="tester" qtp="V9.0">
    <name>item1-name</name>
    <name>item1-name</name>
    <description>item1 Smash</description>
  </item>
   <item1>
    <name>item2-name</name>
    <description>item2 Smash</description>
  </item1>
   <dbconf>
    <name>root</name>
    <passwd>
<passwd1>111111</passwd1>
<passwd2>222222</passwd2>
</passwd>
<IP>1.1.1.1</IP>
  </dbconf>
</PurchaseOrder>'''

#读文件和读xml数据两种方式
#root=ElementTree(file='d:\\book.xml').getroot()
root = ElementTree.fromstring(data)

#获取二级目录下的数据
print root.find('item/name').text
print root.find('item1/name').text

#获取item属性值
print root.find('item').attrib['ty']
print root.find('item').attrib['qtp']

#获取多级目录下的数据
print root.find('dbconf/name').text
print root.find('dbconf/passwd/passwd1').text
print root.find('dbconf/passwd/passwd2').text
print root.find('dbconf/IP').text





TAG:

 

评分:0

我来说两句

Open Toolbar