2017-01-23 11 views
0

XMLファイル内の特定のタグの内容を抽出しようとしています。elementtree:xml文書内の特定のタグの内容を取得

サンプルXML:

<facts> 
     <fact> 
      <name>crash</name> 
      <full_name>Crash</full_name> 
      <variables> 
       <variable> 
        <name>id</name> 
        <proper_name>Crash Instance</proper_name> 
        <type>INT</type> 
        <interpretation>key</interpretation> 
       </variable> 
       <variable> 
        <name>accident_key</name> 
        <proper_name>Case Identifier</proper_name> 
        <interpretation>string</interpretation> 
        <type>CHAR(9)</type> 
       </variable> 
       <variable> 
        <name>accident_year</name> 
        <proper_name>Crash Year</proper_name> 
        <interpretation>dim</interpretation> 
        <type>INT</type> 
       </variable> 
      </variables> 
     </fact> 
    <fact> 
     <name>vehicle</name> 
     <full_name>Vehicle</full_name> 
     <variables> 
      <variable> 
       <name>id</name> 
       <proper_name>Vehicle Instance</proper_name> 
       <type>INT</type> 
      </variable> 
      <variable> 
       <name>crash_id</name> 
        <proper_name>Crash Instance</proper_name> 
       <type>INT</type> 
      </variable> 
     </variables> 
    </fact> 
</facts> 

私はだけクラッシュ実際には、ノードからタグの内容のすべてを引っ張って欲しいです。

ここまでは私のコードです。

def header(filename, fact):  
    lst = [] 
    tree = ET.parse(filename) #read in the XML 
    for fact in tree.iter(tag = 'fact'): 
     factname = fact.find('name').text 
     if factname == fact: #choose the fact to pull from 
      for var in fact.iter(tag = 'variable'): 
       name = var.find('name').text 
       lst.append(name) 
    return lst #return a list of all the <name> tags from the Crash fact 

newlst = header('schema.xml','crash') 

私の出力newlstは、クラッシュ事実のすべてのタグのリストでなければなりません。しかし、それは空に戻り続けます。

Iハードコードすべてを(と機能を削除する)場合には不思議なこと、それが正しい出力を返します:機能で

lst = [] 
tree = ET.parse('schema.xml') 
for fact in tree.iter(tag = 'fact'): 
    factname = fact.find('name').text 
    if factname == 'crash': 
     for var in fact.iter(tag = 'variable'): 
      name = var.find('name').text 
      lst.append(name) 
print(lst) 


Output: ['id', 
'accident_key', 
'accident_year'] 

答えて

3

あなたは、パラメータとして、最初の両方の変数factを使用しています、 forループの変数。このバージョンを試してみてください:

def header(filename, target_factname):  
    lst = [] 
    tree = ET.parse(filename) #read in the XML 
    for fact in tree.iter(tag = 'fact'): 
     factname = fact.find('name').text 
     if factname == target_factname: #choose the fact to pull from 
      for var in fact.iter(tag = 'variable'): 
       name = var.find('name').text 
       lst.append(name) 
    return lst #return a list of all the <name> tags from the Crash fact 
+0

私は愚かな間違いをしていたことを知っていました...ありがとう! – ale19

関連する問題