如何使用python获取父节点下子节点的索引?

时间:2013-09-04 01:27:09

标签: python xml

我的xml文件是这样的:

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

我需要知道父节点'RECORD'中子节点ID =“1”的索引。(在这种情况下索引为0) 请帮我解决这个问题。

谢谢.. :))

1 个答案:

答案 0 :(得分:1)

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

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