user2667397
user2667397

Reputation: 33

how to get the index of a child node under a parent node using python?

my xml file goes like this:

<?xml version="1.0"?>
<BCPFORMAT 
xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
 <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="12"/> 
 <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="20" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
 <FIELD ID="3" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="30" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
</RECORD>
<ROW>
 <COLUMN SOURCE="1" NAME="age" xsi:type="SQLINT"/>
 <COLUMN SOURCE="2" NAME="firstname" xsi:type="SQLVARYCHAR"/>
 <COLUMN SOURCE="3" NAME="lastname" xsi:type="SQLVARYCHAR"/>
</ROW>
</BCPFORMAT>

i need to know the index of the child node ID="1" in its parent node 'RECORD'.(ie, index is 0 in this case) please help me solve this.

thanks.. :)

Upvotes: 3

Views: 6412

Answers (1)

falsetru
falsetru

Reputation: 369364

Using xml.etree.ElementTree:

import xml.etree.ElementTree as ET

root = ET.fromstring('''<?xml version="1.0"?>
<BCPFORMAT 
...
</BCPFORMAT>''')
# Accessing parent node: http://effbot.org/zone/element.htm#accessing-parents
parent_map = {c: p for p in root.getiterator() for c in p}    child = root.find('.//*[@ID="1"]')
print(list(parent_map[child]).index(child)) # => 0

Using lxml:

import lxml.etree as ET

root = ET.fromstring('''<?xml version="1.0"?>
<BCPFORMAT 
...
</BCPFORMAT>''')
child = root.find('.//*[@ID="1"]')
print(child.getparent().index(child)) # => 0

Upvotes: 3

Related Questions