Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if node exists

I am working with IronPython 2.7 in Dynamo. I need to check if a node exists. If so, the text in the node should be written to a list. If no, then False should be written to the list.

I get no error. But, even if a node exists in the list, it doesn't write the text in the list. False is correctly written into the list.

Simple Example:

<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>

So, the node lvl is only in the first node game. I expect the resulting list like list[11111, false].

Here is my code:

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

Why is the list empty where the string should be? I get list[ ,false].

like image 750
Yuli Avatar asked Dec 01 '25 07:12

Yuli


1 Answers

You need to use the text of the match from the elem.find, not the original elem:

 for elem in main_match:
    subelem = elem.find(searchforxpath)
    if subelem != None:
        list.append(subelem.text)  
    else:
        list.append(False)
like image 115
James Doepp - pihentagyu Avatar answered Dec 02 '25 21:12

James Doepp - pihentagyu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!