Elementtree ซ้ำกันซึ่งเป็นผลมาจากโหนดย่อยที่ฝังอยู่

ฉันกำลังพยายามดึงองค์ประกอบต่างๆ จากระบบบันทึกของรัฐสภาอังกฤษ แฮนซาร์ด แต่ xml ไม่ได้มีรูปแบบที่ดีเป็นพิเศษ ตัวอย่างเช่น มีโครงสร้างดังนี้ housecommons/debates/section/section/data housecommons/speeches/section/section/data housecommons/section/section/data

ฉันมีรหัสที่สามารถรับข้อมูลตามตัวอย่างด้านล่าง อย่างไรก็ตาม สิ่งนี้ส่งผลให้เกิดค่าที่ซ้ำกัน ฉันคิดว่าเหตุผลก็คือรหัสของฉันไม่เคารพความสัมพันธ์ระหว่างผู้ปกครองและเด็ก แต่เพียงค้นหาเครื่องหมาย 'ส่วน' แต่ละรายการตามเครื่องหมายแรกแทน

ใครช่วยแนะนำหน่อยว่าฉันสามารถปรับโค้ดของฉันเพื่อหลีกเลี่ยงการซ้ำซ้อนได้อย่างไร

doc = ET.parse(xmlFile)
for house in doc.iter('housecommons'):
    #print ('housecommon', house.tag)
    for debates in house.iter('debates'):
        print ('debates')
        #print (title)
        for section in debates.iter('section'):
            #print ("debates section", section.text)
            #title = ("title", section.find('title').text)
            print('debate section')
            for subsection in debates.iter('section'):
                print("debate subsection", subsection.text)
                #title = ("title", subsection.find('title').text)
                #print(title)

ไม่มี นี่คือประเภทของสิ่งใน raw xml ที่ฉันพยายามแยกวิเคราะห์ หากไม่มีการโพสต์ xml แบบเต็ม โครงสร้างที่ซับซ้อนอาจไม่ปรากฏให้เห็นทั้งหมด


<housecommons>
<image src="S6CV0001P0I0103"/>
<col>181</col>
<title>House of Commons</title>
<date format="1981-03-17">Tuesday 17 March 1981</date>
<p id="S6CV0001P0-00854"><i>The House met at half-past Two o'clock</i></p>
<debates>
<section>
<title>PRAYERS</title>
<p id="S6CV0001P0-00855">[MR. SPEAKER <i>in the Chair</i>]</p>
<section>
<title>PRIVATE BUSINESS</title>
<section>
<title>CHARTERHOUSE JAPHET BILL</title>
<p id="S6CV0001P0-00856"><i>Bill read the Third time and passed, with amendments.</i></p>
<section>
<title>BARNSLEY BOROUGH COUNCIL BILL</title>
<p id="S6CV0001P0-00857"><i>Further considered; to be read the Third time.</i></p>
</section>
</section>
</section>
</section>
</housecommons>

person Ian Stewart    schedule 29.07.2020    source แหล่งที่มา
comment
คุณสามารถแก้ไขคำถามของคุณและตรวจสอบให้แน่ใจว่าตัวอย่าง xml นั้นถูกต้องหรือไม่   -  person Jack Fleeting    schedule 30.07.2020


คำตอบ (1)


เมธอด iter(…) จะวนซ้ำบนแผนผังย่อย XML ทั้งหมดที่อยู่ด้านล่าง (ลูก ๆ ของต้นไม้ ลูก ๆ ของมัน และอื่นๆ)

ฉันคิดว่าคุณอาจต้องการใช้โครงสร้างเช่นนี้

for child in parent:
    if child.tag == 'debates':
         # look further

เมธอด iter(…) มีความลึกมากกว่าหนึ่งระดับในการค้นหาชื่อแท็กที่คุณระบุ นี่คือสาเหตุว่าทำไมรายการซ้ำจึงปรากฏขึ้น

person JimmyNJ    schedule 30.07.2020