2017-06-13 68 views
0

我使用Python(minidom命名)解析XML文件和打印輸出就像一個CSV文件XML嵌套變量麻煩:Python的 - 使用minidom命名

0.0,0.0,51.3,46.6, 
49.9,49.0,51.0,46.6, 
36.0,24.0,47.8,42.2, 
51.0,46.6,49.3,34.1, 

相反,程序生成以下,跳過'Q'標籤,除非它們是各自'Event'標籤中的最後一個標籤...爲什麼我的程序無法打印這些標籤?

0.0,0.0,,46.6 
49.9,49.0,, 
36.0,24.0,42.2, 
51.0,46.6,, 

這裏是XML源文件:

<?xml version="1.0" encoding="UTF-8"?> 
<Games id = "1"> 
    <Game id="1" competition_id="1"> 
    <Event id="0" x="0.0" y="0.0"> 
     <Q id="a" end_x="51.3" /> 
     <Q id="b" end_y="46.6" /> 
    </Event> 
    <Event id="1" x="49.9" y="49.0"> 
     <Q id="a" end_x="51.0" /> 
     <Q id="b" end_y="46.6" /> 
     <Q id="c" q1="tap" /> 
    </Event> 
    <Event id="2" x="0.0" y="0.0"> 
     <Q id="a" end_y="47.8" /> 
     <Q id="b" end_x="42.2" /> 
    </Event> 
    <Event id="3" x="51.0" y="46.6"> 
     <Q id="a" end_y="49.3" /> 
     <Q id="b" end_x="34.1" /> 
     <Q id="c" q1="17.8" /> 
    </Event> 
</Game> 

這裏是我的代碼:

from xml.dom.minidom import parse 
import xml.dom.minidom 

DOMTree = parse('myfile.xml'); 
collection = DOMTree.documentElement; 

# Get all events in the collection 
events = collection.getElementsByTagName("Event") 

# Iterate through events 
for event in events: 
    start_x = event.getAttribute('x'); 
    start_y = event.getAttribute('y'); 

    qualifiers = event.getElementsByTagName('Q'); 

    # Iterate through qualifiers 

    for qualifier in qualifiers: 
     end_x= qualifier.getAttribute('end_x'); 
     end_y= qualifier.getAttribute('end_y'); 

    print start_x + ',' + start_y + ',' + end_x + ',' + end_y 

回答

1

如果你看看你的結構預選賽預選賽循環中,循環內的end_x和end_y沒有任何反應。這意味着代碼將運行並重新分配end_x和end_y的值。在循環,end_x和end_y月底是最後預選賽

from xml.dom.minidom import parse 
import xml.dom.minidom 

DOMTree = parse('myfile.xml'); 
collection = DOMTree.documentElement; 

# Get all events in the collection 
events = collection.getElementsByTagName("Event") 

# Iterate through events 
for event in events: 
    start_x = event.getAttribute('x'); 
    start_y = event.getAttribute('y'); 

    qualifiers = event.getElementsByTagName('Q'); 

    # Iterate through qualifiers 

    for qualifier in qualifiers: 
     if(qualifier.hasAttribute('end_x')): 
      end_x= qualifier.getAttribute('end_x'); 
     elif(qualifier.hasAttribute('end_y')): 
      end_y= qualifier.getAttribute('end_y'); 

    print start_x + ',' + start_y + ',' + end_x + ',' + end_y 

的上面的代碼應該做你想要的值。我注意到的一點是,最初命令是end_x,然後是end_y,然後命令改變了end_y end_x,所以在樣本正確的格式中,結束座標被翻轉。所以輸出

0.0,0.0,51.3,46.6, 
49.9,49.0,51.0,46.6, 
36.0,24.0,42.2,47.8, 
51.0,46.6,34.1,49.3, 

希望這有助於