【问题标题】:Check if node exists检查节点是否存在
【发布时间】:2017-06-03 04:43:29
【问题描述】:

我正在 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]

【问题讨论】:

    标签: python xml python-2.7 exists


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的帮助!这正是我需要的:)
    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多