#encoding=utf-8 import os import xml.etree.ElementTree as ET import pandas as pd import csv def xml2csv(xmlpath): tree_obj = ET.parse(xmlpath) # 得到所有匹配Region 标签的Element对象的list集合 list_Region = tree_obj.findall("Region") for Region in list_Region: # 几何面对应的类(phenology_name)在标签 Region_dict = Region.attrib phenology_name = Region_dict.get("name") print(phenology_name) list_GeometryDef = Region.findall("GeometryDef") list_Polygon = list_GeometryDef[0].findall("Polygon") # 获得该类下的几何面list for polygon in list_Polygon: # 从polygon list中获取得到标签的数据 注意是空格分隔的和csv中不同 Coordinates_list = coordinates = polygon.find('.//Coordinates').text.strip().split() # POLYGON((119.035 31.51,119.035 31.50,119.033 31.50)) csv中 print("value") # 向csv中写 def csvfile(csvpath,data): with open(csvpath, 'a', newline='') as file: # 2. step writer = csv.writer(file) # data example #data = ["This", "is", "a", "Test"] writer.writerow(data) # Define the structure of the data #data示例 student_header = ['name', 'age', 'major', 'minor'] def csvcreateTitile(csvpath,data): # 1. Open a new CSV file with open(csvpath, 'w') as file: # 2. Create a CSV writer writer = csv.writer(file) # 3. Write data to the file writer.writerow(data) # 将列表中的坐标对转换为字符串 def createcsv_roi_polygon(coordinates): coord_str = ','.join([f'{coordinates[i]} {coordinates[i + 1]}' for i in range(0, len(coordinates), 2)]) # 构建最终的POLYGON字符串 polygon_str = f'POLYGON(({coord_str}))' print(polygon_str) return polygon_str def get_Azimuth_incidence(Azimuth_path): Azimuth_incidence = 0 if not os.path.exists(Azimuth_path): print('get Azimuth_incidence failed!') return Azimuth_incidence with open(Azimuth_path) as f: Azimuth_incidence = f.readline() return Azimuth_incidence # if __name__ == '__main__': # path = r"D:\micro\WorkSpace\Ortho1\Temporary\test.txt" # value = get_Azimuth_incidence(path) # print(value) if __name__ == '__main__': xmlpath = r"E:\MicroWorkspace\S_SAR\AHV\landCover.xml" tree_obj = ET.parse(xmlpath) csv_header = ['sar_img_name', 'phenology_id', 'phenology_name', 'roi_polygon'] csvpath = r"E:\MicroWorkspace\S_SAR\AHV\newimage.csv" # csvcreateTitile(csvpath,csv_header) csvfile(csvpath,csv_header) # 得到所有匹配Region 标签的Element对象的list集合 list_Region = tree_obj.findall("Region") name_list = {} count = 10 for Region in list_Region: # 几何面对应的类(phenology_name)在标签 Region_dict = Region.attrib phenology_name = Region_dict.get("name") if not phenology_name in name_list.keys(): name_list.update({phenology_name: count}) count += 10 print(phenology_name) # list_GeometryDef = Region.findall("GeometryDef") list_Polygon = Region.findall(".//Polygon") # 获得该类下的几何面list for polygon in list_Polygon: # 从polygon list中获取得到标签的数据 注意是空格分隔的和csv中不同 Coordinates_list = coordinates = polygon.find('.//Coordinates').text.strip().split() # 将坐标和ploygon对应的写入到.csv中 polygon_str=createcsv_roi_polygon(Coordinates_list) # POLYGON((119.035 31.51,119.035 31.50,119.033 31.50)) csv中 data = ['0', name_list.get(phenology_name), phenology_name, polygon_str] csvfile(csvpath, data)