我在 Dynamo 中使用 IronPython 2.7。 我需要从一个非常大的 xml 中的特定注释中获取值。我做了一个示例 xml,所以你可以更好地理解问题。 所以我需要得到“lvl”的值,但只在注释“to”中。
在我收到错误的那一刻:
TypeError: list objects are unhashable"
对于行:
list.extend(elem.findall(match))
我做错了什么?有更好/更简单的方法吗?
这是示例 xml:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<note2>
<yolo>
<to>
<type>
<game>
<name>Jani</name>
<lvl>111111</lvl>
<fun>2222222</fun>
</game>
</type>
</to>
<mo>
<type>
<game>
<name>Bani</name>
<lvl>3333333</lvl>
<fun>44444444</fun>
</game>
</type>
</mo>
</yolo>
</note2>
</note>
这是我的代码:
import clr
import sys
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
sys.path.append("C:\Program Files (x86)\IronPython 2.7\Lib")
import xml.etree.ElementTree as ET
xml="note.xml"
xpathstr=".//yolo"
match ="lvl"
list=[]
tree = ET.parse(xml)
root = tree.getroot()
specific = root.findall(xpathstr)
for elem in specific:
list.extend(elem.findall(match))
print tree, root, specific, list
请您参考如下方法:
如果你需要获取“lvl”的值,但只能在注释“to”中,你可以在一个 xpath 中完成:
import xml.etree.ElementTree as ET
xml="note.xml"
xpathstr=".//to//lvl"
tree = ET.parse(xml)
root = tree.getroot()
specific = root.findall(xpathstr)
list=[]
for elem in specific:
list.append(elem.text)
print (list)
给予:
['111111']
如果您知道元素“type”和“game”包含“lvl”,您可以选择使用 xpath“.//to/type/game/lvl”,或者如果元素“to”必须包含在“yolo”然后使用“.//yolo/to/type/game/lvl”
您可能想使用 list.append 而不是 list.extend,但也许不想,我不知道您的其余代码。
