Home > Software design >  Replacing KML Sub-Tag Value
Replacing KML Sub-Tag Value

Time:06-29

I am trying to replace the first six characters of a sub-tag <color></color> value in a KML file:

Current:

<Style id='1'>
        <LineStyle>
                <color>9900e6ff</color>
                <width>2</width>
        </LineStyle>

Expected:

<Style id='1'>
        <LineStyle>
                <color>ffffffff</color>
                <width>2</width>
        </LineStyle>

Attempted sed Code:

sed -i s/<LineStyle><color>[0-9]*</color></LineStyle>/<LineStyle><color>ffffff[0-9][a-z]</color></LineStyle>/g' file.kml

CodePudding user response:

I recommend as other commentators not to use regex for element search because of possible unpredictable behavior & it is better to prefer any package with xpath such as lxml or xml.

from lxml import etree as ET

some_xml = """
<Style id='1'>
    <LineStyle>
        <color>9900e6ff</color>
        <width>2</width>
    </LineStyle>
</Style>
"""

some_xml = ET.fromstring(some_xml)
if len(result := some_xml.xpath("descendant::color")) == 1:
    result[0].text = "ffffffff"
    print(ET.tostring(some_xml, encoding="unicode"))
  • Related