工作中需要读取指定xml数据库中的数据以及 表所需字段名,所以在已有例子中改进实现:
xml 数据库 xmldabase.xml:
获取指定表的数据:
from xml.etree import ElementTree
def get_table_records( xmlfile = None,text = None,table_name=None):
root=None
if xmlfile:
root = ElementTree.parse(xmlfile)
elif text:
root = ElementTree.fromstring(text)
node_findall = root.findall("table")
for e in node_findall:
for key,value in e.items():
if value==table_name:
print( "%s:%s" % (key, value) )
ar=e.findall('row')
for row in ar:
for k,v in row.items():
print( "%s:%s" % (k, v) )
获取所有表的字段名称:
def get_table_field(text =None, xmlfile =None):
root=None
if xmlfile:
root = ElementTree.parse(xmlfile)
elif text:
root = ElementTree.fromstring(text)
node_findall = root.findall("table")
for e in node_findall:
list_field=[]
for key,value in e.items():
# print( "%s:%s" % (key, value) )
first_row=e.find('row')
# print(type(first_row))
if first_row==None :
print('%s_need_fields=%s'%(value,list_field))
# continue
else:
for k,v in first_row.items():
list_field.append(k)
# print( "%s:%s" % (k, v) )
print('%s_need_fields=%s'%(value,list_field))
测试用例:
if __name__ == '__main__':
# get_table_records(text=open("xmldabase.xml").read(),table_name='PCI') #获取xml的方式不同,皆可用
get_table_records(xmlfile="xmldabase.xml",table_name='PCI')
get_table_field(xmlfile="xmldabase.xml")
输出结果:
name:PCI
class_name:Display controller
vendor_id:1a03
__mtime:8489775
host:OpaqueRef:d92d7211-482f-c68f-f89b-4c8b22faec1a
dependencies:()
_ref:OpaqueRef:1e2c98ee-a6fe-b1d5-e91c-d27911deb21d
device_id:2000
functions:1
uuid:5907d30d-7d53-4682-4ff1-ed32974cb3b6
class_id:03
other_config:()
__ctime:8489729
pci_id:0000:09:00.0
device_name:ASPEED Graphics Family
attached_VMs:()
vendor_name:ASPEED Technology, Inc.
ref:OpaqueRef:1e2c98ee-a6fe-b1d5-e91c-d27911deb21d
PCI_need_fields=['class_name', 'vendor_id', '__mtime', 'host', 'dependencies', '_ref', 'device_id', 'functions', 'uuid', 'class_id', 'other_config', '__ctime', 'pci_id', 'device_name', 'attached_VMs', 'vendor_name', 'ref']
xx_metrics_need_fields=['last_updated', 'vendor_id', '__mtime', '_ref', 'device_name', 'speed', 'device_id', 'uuid', 'duplex', 'other_config', '__ctime', 'pci_bus_path', 'io__write_kbs', 'carrier', 'io__read_kbs', 'vendor_name', 'ref']