dms-client/util/xml_util.py

50 lines
3.1 KiB
Python
Raw Normal View History

"""
Author : XinYi Song
Time : 2021/10/12 11:13
Desc: xml工具类
"""
from xml.dom.minidom import parseString
import dict2xml
import xmltodict
import json
import os
# 初始化数据传入参数1、xml文件路径 2、xml格式字符串 3、json字符串 4、dict字典
def init_data(file_Str_Dict):
if isinstance(file_Str_Dict, str) and os.path.isfile(file_Str_Dict):
with open(file_Str_Dict) as fp:
data = fp.read()
return data
elif isinstance(file_Str_Dict, (str, dict)):
data = file_Str_Dict
return data
# 读取xml文件转换成字典
def xml_to_dict(file_Str_Dict):
data = init_data(file_Str_Dict)
data_orderedD = xmltodict.parse(data)
data_json = json.dumps(data_orderedD, indent=4)
data_dict = json.loads(data_json)
return data_dict
# 将字典写入到xml中并保存
def dict_to_xml(dict_in, xml_out):
xml_str = dict2xml.dict2xml(dict_in)
xml_raw = '<?xml version="1.0" encoding="utf-8"?>\n' + '<xml>\n' + xml_str + '\n</xml>'
dom = parseString(xml_raw.replace('\n', ''))
pretty = dom.toprettyxml(indent=" ", newl="\n", encoding="utf-8")
with open(xml_out, 'w') as f:
f.write(pretty.decode("utf-8"))
f.close()
if __name__ == '__main__':
d = xml_to_dict("E:/xmltest/demo.xml")
print(d)
# a = {'ProductMetaData': {'SatelliteID': 'GF1', 'SensorID': 'PMS1', 'ReceiveTime': '2013-11-05 05:52:11', 'OrbitID': '2850', 'ProduceType': 'STANDARD', 'SceneID': '154627', 'ProductID': '107383', 'ProductLevel': 'LEVEL1A', 'ProductQuality': None, 'ProductQualityReport': None, 'ProductFormat': 'GEOTIFF', 'ProduceTime': '2013-11-05 17:27:10', 'Bands': '1,2,3,4', 'ScenePath': '65', 'SceneRow': '177', 'SatPath': '65', 'SatRow': '177', 'SceneCount': '1', 'SceneShift': '1', 'StartTime': '2013-11-05 13:52:08', 'EndTime': '2013-11-05 13:52:14', 'CenterTime': '2013-11-05 13:52:11', 'ImageGSD': '8', 'WidthInPixels': '4548', 'HeightInPixels': '4500', 'WidthInMeters': None, 'HeightInMeters': None, 'CloudPercent': '0', 'QualityInfo': None, 'PixelBits': None, 'ValidPixelBits': None, 'RollViewingAngle': '0', 'PitchViewingAngle': '0', 'RollSatelliteAngle': '9.56992e-05', 'PitchSatelliteAngle': '0.000105642', 'YawSatelliteAngle': '2.91257', 'SolarAzimuth': '169.08', 'SolarZenith': '33.6357', 'SatelliteAzimuth': '81.7259', 'SatelliteZenith': '88.1627', 'GainMode': 'G0,G4,G0,G0', 'IntegrationTime': '0.00115931', 'IntegrationLevel': 'S5,S3,S4,S3', 'MapProjection': None, 'EarthEllipsoid': None, 'ZoneNo': None, 'ResamplingKernel': None, 'HeightMode': None, 'MtfCorrection': 'LAB', 'RelativeCorrectionData': None, 'TopLeftLatitude': '40.1695', 'TopLeftLongitude': '78.2523', 'TopRightLatitude': '40.0948', 'TopRightLongitude': '78.6629', 'BottomRightLatitude': '39.7655', 'BottomRightLongitude': '78.5609', 'BottomLeftLatitude': '39.84', 'BottomLeftLongitude': '78.1522', 'TopLeftMapX': None, 'TopLeftMapY': None, 'TopRightMapX': None, 'TopRightMapY': None, 'BottomRightMapX': None, 'BottomRightMapY': None, 'BottomLeftMapX': None, 'BottomLeftMapY': None}}
# dict_to_xml(a, './res.xml')