简体   繁体   English

python XML查找和替换

[英]python XML find and replace

After fighting a day with python / etree without considerable success: 在用python / etree奋斗了一天之后,没有取得太大的成功:

I have a xml file (items.xml) 我有一个xml文件(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" 查找所有父元素名为“ layer”且其类别为“ SvgMarker”的道具元素
  3. multiply the value of v with 1.5 将v的值乘以1.5
  4. write the content back 写回内容

I do not stick on etree if there is something easier. 如果有更简单的方法,我不会坚持使用etree。

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 参考: https : //docs.python.org/2/library/xml.etree.elementtree.html#example

You need to take care of hierarchy in xml tags and their type conversion to perform multiplication. 您需要注意xml标记中的层次结构及其类型转换,以执行乘法。 I tested below code with your xml, it works fine. 我用您的xml测试了以下代码,效果很好。

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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM