-1

After fighting a day with python / etree without considerable success:

I have a xml file (items.xml)

<symbols>
    <symbol>
        <layer class="SvgMarker">
            <prop k="size" v="6.89"/>
        </layer>
    </symbol>
    <symbol>
        <layer class="SvgMarker">
            <prop k="size" v="3.56"/>
        </layer>
    </symbol>
    <symbol>
        <layer class="line">
            <prop k="size" v="1"/>
        </layer>
    </symbol>            
</symbols>

Questions

  1. read this file
  2. find all prop elements which have a parent element namend "layer" with class "SvgMarker"
  3. multiply the value of v with 1.5
  4. write the content back

I do not stick on etree if there is something easier.

2 Answers 2

1

This would help you

import xml.etree.ElementTree as ET

tree = ET.parse('items.xml') # Path to input file
root = tree.getroot()

for prop in root.iter('.//*[@class="SvgMarker"]/prop'):
   prop.set('v', str(float(prop.get('v')) * 1.5))

tree.write('out.xml', encoding="UTF-8")

Ref: https://docs.python.org/2/library/xml.etree.elementtree.html#example

0
0

You need to take care of hierarchy in xml tags and their type conversion to perform multiplication. I tested below code with your xml, it works fine.

import xml.etree.ElementTree as ET
tree = ET.parse('homemade.xml')                 #Step 1
root = tree.getroot()
for symbol in tree.findall('symbol'):
    for layer in symbol.findall('layer'):
        class_ = layer.get('class')
        if(class_=="SvgMarker"):                #Step 2
            for prop in layer.findall('prop'):
                new_v = prop.get('v')
                new_v = float(new_v)*1.5        #Step 3
                prop.set('v',str(new_v))
outFile = open('homemade.xml', 'w')
tree.write(outFile)                             #Step 4

Hope this helps.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.