0

I have an XML file that I need to change only 2 attributes inside :

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
    <name>lines.kmz</name>
    <Style id="LineStyle00">
        <LabelStyle>
            <color>00000000</color>
            <scale>0</scale>
        </LabelStyle>
..............

All I need to change is the colo and scale inside the labelstyle tag.

here is what I have tried :

import xml.etree.ElementTree as ET

def update_label_style(kml_path, new_color, new_scale):
    # parse the KML file
    tree = ET.parse(kml_path)
    root = tree.getroot()

    # define the namespace for KML elements
    ns = {'kml': 'http://www.opengis.net/kml/2.2'}

    # find all LabelStyle elements and update their color and scale values
    for label_style in root.findall('.//kml:LabelStyle', ns):
        label_style.find('kml:color', ns).text = new_color
        label_style.find('kml:scale', ns).text = new_scale

    # write the updated KML file back to disk
    tree.write(kml_path, encoding='utf-8', xml_declaration=True)
    print("Changed the label style")

after the edits done the XML file are like :

<?xml version='1.0' encoding='utf-8'?>
<ns0:kml xmlns:ns0="http://www.opengis.net/kml/2.2">
<ns0:Document>
    <ns0:name>lines.kmz</ns0:name>
    <ns0:Style id="LineStyle00">
        <ns0:LabelStyle>

the problem is that it has added ns0 before every tag, also it has removed an entire line which is

<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
mzjn
  • 48,958
  • 13
  • 128
  • 248
Ahmed Wagdi
  • 3,913
  • 10
  • 50
  • 116
  • 1
    Since you don't want any prefix, use `register_namespace("", "http://www.opengis.net/kml/2.2")`; very similar to this answer: https://stackoverflow.com/a/68470618/407651. – mzjn Apr 09 '23 at 12:40
  • Also note that ElementTree removes declarations for namespaces that are not actually used. See https://stackoverflow.com/q/45990761/407651. – mzjn Apr 09 '23 at 13:03

0 Answers0