|
| 1 | +import xml.etree.ElementTree as ET |
| 2 | +from typing import Dict |
| 3 | +import zipfile |
| 4 | + |
| 5 | + |
| 6 | +def read_xml_tree_from_qgz(qgz_path: str) -> ET.Element: |
| 7 | + qgs_filename = next( |
| 8 | + (name for name in zipfile.ZipFile(qgz_path).namelist() if name.endswith(".qgs")), |
| 9 | + None, |
| 10 | + ) |
| 11 | + |
| 12 | + if qgs_filename is None: |
| 13 | + raise ValueError(f"No .qgs file found inside {qgz_path}") |
| 14 | + |
| 15 | + with zipfile.ZipFile(qgz_path, "r") as input_zip_file: |
| 16 | + entries = {name: input_zip_file.read(name) for name in input_zip_file.namelist()} |
| 17 | + |
| 18 | + return ET.fromstring(entries[qgs_filename]) |
| 19 | + |
| 20 | + |
| 21 | +def is_qgis_version_4(qgz_file: str) -> bool: |
| 22 | + root = read_xml_tree_from_qgz(qgz_file) |
| 23 | + |
| 24 | + version = root.attrib.get("version", "") |
| 25 | + if not version.startswith("4."): |
| 26 | + return False |
| 27 | + |
| 28 | + return True |
| 29 | + |
| 30 | + |
| 31 | +def parse_properties(element, prefix="") -> Dict: |
| 32 | + """Recursively parse nested <properties> elements into a flat dict with path keys.""" |
| 33 | + result = {} |
| 34 | + |
| 35 | + for child in element: |
| 36 | + if child.tag != "properties": |
| 37 | + continue |
| 38 | + |
| 39 | + name = child.attrib.get("name", "") |
| 40 | + key = f"{prefix}/{name}" if prefix else name |
| 41 | + prop_type = child.attrib.get("type") |
| 42 | + |
| 43 | + if prop_type is not None: |
| 44 | + if prop_type == "QStringList": |
| 45 | + result[key] = [v.text for v in child.findall("value")] |
| 46 | + else: |
| 47 | + result[key] = child.text |
| 48 | + else: |
| 49 | + result.update(parse_properties(child, prefix=key)) |
| 50 | + |
| 51 | + return result |
| 52 | + |
| 53 | + |
| 54 | +def read_mergin_properties(qgz_file: str) -> Dict: |
| 55 | + root = read_xml_tree_from_qgz(qgz_file) |
| 56 | + |
| 57 | + version = root.attrib.get("version", "") |
| 58 | + if not version.startswith("4."): |
| 59 | + return {} |
| 60 | + |
| 61 | + mergin_elem = root.find(".//properties[@name='Mergin']") |
| 62 | + if mergin_elem is None: |
| 63 | + return {} |
| 64 | + |
| 65 | + props = parse_properties(mergin_elem) |
| 66 | + |
| 67 | + return props |
0 commit comments