Skip to main content
 首页 » 编程设计

python之如何使用 Python 的 ElementTree 获取 child 的子元素

2025年01月19日9cmt

XML 看起来更像这样:

<root> 
<course> 
   <reg_num>10577</reg_num> 
   <subj>ANTH</subj> 
   <crse>211</crse> 
   <sect>F01</sect> 
   <title>Introduction to Anthropology</title> 
   <units>1.0</units> 
   <instructor>Brightman</instructor> 
   <days>M-W</days> 
   <time> 
       <start_time>03:10PM</start_time> 
       <end_time>04:30</end_time> 
   </time> 
   <place> 
       <building>ELIOT</building> 
       <room>414</room> 
   </place> 
</course> 
<root> 

然后这是我获取标题等的代码....我想获取具有子元素的时间或地点标签。我该怎么做,我也尝试了不同的方法,但似乎都没有用。谢谢你!感谢任何帮助

for c in courses: 
    title = c.find('title').text 
    num = c.find('crse').text 
    days = c.find('days').text 
    # time = c.find('time').text 
 
    # for t in c: 
    #     timeSlot1 = t.find('start_time') 
    #     timeSlot2 = t.find('end_time') 
 
 
        # format text using {} 
        print(' *{} {} [{}] {} {} {}'.format(b, title, days, num, timeSlot1, timeSlot2)) 
 
 
    # how to get date 

请您参考如下方法:

您就快完成了:只需通过指定相对于 <course> 的路径来选择正确的 child :

for c in courses: 
    title = c.find('title').text 
    # [...] 
 
    timeSlot1 = c.find('time/start_time').text 
    timeSlot2 = c.find('time/end_time').text