2017-02-09 10 views
0

複数のレベルのタグを持つxmlファイルからフィールドを抽出しようとしています。次の例では、 PythonマルチレベルタグのXML解析

<compound kind="struct"> 
    <name>my-struct</name> 
    <filename>struct____dt__args.html</filename> 
    <member kind="variable"> 
     <type>int32_t</type> 
     <name>count</name> 
     <anchorfile>struct____dt__args.html</anchorfile> 
     <anchor>a0fbe49d8b1189286bd817409658eb631</anchor> 
     <arglist></arglist> 
    </member> 
    <member kind="variable"> 
     <type>int32_t</type> 
     <name>create_type</name> 
     <anchorfile>struct____dt__args.html</anchorfile> 
     <anchor>a4e38c7f138891d020cce3c6d7e6bc31e</anchor> 
     <arglist></arglist> 
    </member> 
    <member kind="variable"> 
     <type>size_t</type> 
     <name>total_size</name> 
     <anchorfile>struct____dt__args.html</anchorfile> 
     <anchor>a41ca25bca63ad1fee790134901d8d1c0</anchor> 
     <arglist></arglist> 
    </member> 
    </compound> 

は、私はこれを解析し、私は唯一の種類=構造体タグを必要とする(等の異なる種類の構造体/機能/クラスを持つ複数の化合物のタグがある)「化合物」タグ内のフィールドを抽出する必要がありますそれに子の「メンバー」タグのタイプと名前が続きます。ここで

struct my-struct: 
int32_t count 
int32_t create_type 
size_t total_size 

答えて

0

は、ソリューションです:

from xml.etree import ElementTree 


def extract_structs(xml_path): 
    # data and xml structure validation omitted 
    # result collected as lists and tuples without string formatting 
    struct_list = [] 
    root = ElementTree.parse(xml_path).getroot() 
    for compound in root: 
     kind = compound.get('kind') 
     if kind != 'struct': 
      continue 
     current_struct = [] 
     struct_list.append(current_struct) 
     struct_name = compound.find('./name').text 
     current_struct.append((kind, struct_name)) 
     for member in compound.findall('./member'): 
      member_type = member.find('./type').text 
      member_name = member.find('./name').text 
      current_struct.append((member_type, member_name)) 
    return struct_list 


if __name__ == '__main__': 
    structs = extract_structs('test_file.xml') 
    print(structs) 
+0

これは私のためだけの空のリストを出力します。 – marc

+0

おそらく、あなたはルート要素内に名前空間を持っているかもしれませんし、ルートの直接の子要素ではない化合物かもしれません。私のコードは、あなたの文脈に関する未定の前提に基づいていました。完全なXML構造を表示してください。 –