#encoding=utf-8 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 if __name__ == '__main__': xmlpath = r"F:\MicroWorkspace\Micro\likun-GF3-VegetationP\vegTest.xml" tree_obj = ET.parse(xmlpath) csv_header = ['sar_img_name', 'phenology_id', 'phenology_name', 'roi_polygon'] csvpath = r"F:\MicroWorkspace\Micro\likun-GF3-VegetationP\vegTest.csv" # csvcreateTitile(csvpath,csv_header) csvfile(csvpath,csv_header) # 得到所有匹配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 = Region.findall(".//Polygon") # 获得该类下的几何面list count = 1 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', count, phenology_name, polygon_str] csvfile(csvpath,data) count += 1