检查节点是否存在

Check if node exists

我正在 Dynamo 中使用 IronPython 2.7。我需要检查一个节点是否存在。如果是这样,节点中的文本应该写入列表。如果否,则应将 False 写入列表。

我没有收到任何错误。但是,即使列表中存在一个节点,它也不会在列表中写入文本。 False 被正确写入列表。

简单示例:

<note>
    <note2>
        <yolo>
            <to>
                <type>
                    <game>
                        <name>Jani</name>
                        <lvl>111111</lvl>
                        <fun>2222222</fun>
                    </game>
                </type>
            </to>
            <mo>
                <type>
                    <game>
                        <name>Bani</name>
                        <fun>44444444</fun>
                    </game>
                </type>
            </mo>
        </yolo>
    </note2>
</note>

所以,节点lvl只在第一个节点game中。我希望结果列表像 list[11111, false].

这是我的代码:

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"

main_xpath=".//game"
searchforxpath =".//lvl"

list=[]

tree = ET.parse(xml)
root = tree.getroot()

main_match = root.findall(main_xpath)

for elem in main_match:
if elem.find(searchforxpath) is not None:
    list.append(elem.text)  
else:
    list.append(False)

print  list

为什么列表在应该是字符串的地方是空的?我得到 list[ ,false].

您需要使用来自 elem.find 的匹配文本,而不是原始元素:

 for elem in main_match:
    subelem = elem.find(searchforxpath)
    if subelem != None:
        list.append(subelem.text)  
    else:
        list.append(False)