python 2.7 xml - 从注释下方的特定注释中获取值

python 2.7 xml - get the value from a specific note below a note

他我在 Dynamo 中使用 IronPython 2.7。 我需要从一个非常大的 xml 中的特定音符中获取值。我做了一个例子xml,这样你就可以更好地理解问题了。 所以我需要获取 "lvl" 的值,但只在注释 "to".

在我得到错误的那一刻:

TypeError: list objects are unhashable"

对于行:

list.extend(elem.findall(match))

我做错了什么?有 better/easy 的方法吗?

这里是例子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 但也许不是,我不知道您的其余代码。