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

时间:2018-02-01 19:14:23

标签: python xml elementtree

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

1 个答案:

答案 0 :(得分:1)

你几乎就在那里:只需通过指定相对于<course>的路径来选择正确的孩子:

for c in courses:
    title = c.find('title').text
    # [...]

    timeSlot1 = c.find('time/start_time').text
    timeSlot2 = c.find('time/end_time').text