检查节点是否存在。

3

我在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]
1个回答

2
你需要使用elem.find返回的匹配文本,而不是原始的elem文本:
 for elem in main_match:
    subelem = elem.find(searchforxpath)
    if subelem != None:
        list.append(subelem.text)  
    else:
        list.append(False)

谢谢你的帮助!这正是我所需要的 :) - Yuli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接