如何在 python 中编辑 XML 文件

问题描述 投票:0回答:0

我有一个 XML 文件,我只需要更改其中的 2 个属性:

<?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>
..............

我需要更改的是

colo
标签内的
scale
labelstyle

这是我试过的:

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")

编辑完成后,XML 文件如下:

<?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>

问题是它在每个标签之前添加了

ns0
,它还删除了整行

<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">
python xml elementtree xml-namespaces
© www.soinside.com 2019 - 2024. All rights reserved.