2

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

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

谢谢.. :)

4

1 回答 1

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
于 2013-09-04T01:40:59.383 回答