0

此 XML 文档包含一组标记events-data。我想从最近的 RECENT 中提取信息events-data。例如,在下面的代码中,我想去到最后一个 events-data标签,往下到event-date标签并提取date子标签的文本。目前我在 Python 中使用 BeautifulSoup 来遍历这个文档。有任何想法吗?

    <?xml version="1.0" encoding="UTF-8"?>
        <first-tag>
          <second-tag>
            <events-data>
               <event-date>
                    <date>20040913</date>
               </event-date>
            </events-data>

          <events-data> #the one i want to traverse to grab date text
             <event-date>
               <date>20040913</date>
             </event-date>
          </events-data> 
         </second-tag>
       </first-tag>
4

1 回答 1

1

这是使用 BeautifulSoup 3

import os
import sys

# Import Custom libraries
from BeautifulSoup import BeautifulStoneSoup

xml_str = \
'''
<?xml version="1.0" encoding="UTF-8"?>
    <first-tag>
      <second-tag>
        <events-data>
           <event-date>
                <date>20040913</date>
           </event-date>
        </events-data>

      <events-data>
         <event-date>
           <date>20040913</date>
         </event-date>
      </events-data> 
     </second-tag>
   </first-tag>
'''
soup = BeautifulStoneSoup(xml_str)

event_data_location = lambda x: x.name == "events-data"

events = soup.findAll(event_data_location)
if(events):
    # The last event-data
    print events[-1].text
于 2013-07-04T00:02:38.240 回答