我试着写一个可以改变xml文件中的值的脚本,但是文件结构非常困难。我需要编辑XML行"r2dd“中的值: 10.0;10.0;26.0;14.0。我不能把它们赋给一个变量。
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<objects fpmi.archive.type="components" framework.version="7.9.8.2018060714" fpmi.version="9.9.8.0" timestamp="Thu Sep 27 15:00:19 CEST 2018">
<arraylist len="0"/>
<c cls="com.inductiveautomation.factorypmi.application.components.template.TemplateHolder">
<c-comm>
<p2df>26.0;14.0</p2df>
<r2dd>10.0;10.0;26.0;14.0</r2dd>
<str>X123_C61023</str>
<lc>10.0;10.0;16;0;0.7058824;1.3333334</lc>
</c-comm>
<c-c m="setParameterValues" s="1;java.util.Map">
<o cls="java.util.HashMap">
<o-c m="put" s="2;O;O">
<str>tagPath</str>
<str>X123_X123_C61023</str>
</o-c>
</o>
</c-c>
<c-c m="setTemplatePath" s="1;str">
<str>[network]premium/aw1/tags/monitors</str>
</c-c>
</c>
这是我的代码:
import xml.etree.ElementTree as ET
mytree = ET.parse('sample.xml')
myroot = mytree.getroot()
for x in myroot.findall('c'):
other=x.find('c-comm').getchildren()
print('values : ', other)
other_value=other.get('type')
print(other_value)
有人能帮我把这个值从"r2dd“xml行分配给一个变量吗?此时控制台仅显示:
other_value=other.get('type')
AttributeError: 'list' object has no attribute 'get'
values : [<Element 'p2df' at 0x035753C0>, <Element 'r2dd' at 0x03575410>, <Element 'str' at 0x03575438>, <Element 'lc' at 0x03575488>]
但是没有价值。请帮帮忙
(我只能使用getchildren()来访问这个元素...但这是一种错误的方式)。
发布于 2020-03-21 08:12:52
我认为这是因为您没有索引返回getchildren的列表。
other=x.find('c-comm').getchildren()
print('values : ', other)
other_value=other.get('type')
正如您在这一部分中所看到的,您将孩子的列表存储在other中,然后将此变量视为一个孩子。并且可以在你发布的照片中观察到:
values : [<Element 'p2df' at 0x035753C0>, <Element 'r2dd' at 0x03575410>, <Element 'str' at 0x03575438>, <Element 'lc' at 0x03575488>]
因此,您要查找该列表的第二个元素。
https://stackoverflow.com/questions/60782921
复制相似问题