Разбор XML с использованием красивого супа - зацикливание / выравнивание данных - PullRequest
0 голосов
/ 06 сентября 2018

У меня есть XML-файл, который выглядит примерно так

<xml>
   <description> this is a description</description>
       <foo>
          <main_title>this is a main title</main_title>
             <listings>
                 <a_listing>
                     <sub_title>this is a sub title</sub_title>
                        <info name = "Bob" />
                        <info name = "Ann"/>
                 </a_listing>

        <a_listing>
             <sub_title>this is a different sub title</sub_title>
                  <info name = “Peter” />
                  <info name = “Steve”/>
         </a_listing>

              </listings>
        </foo>

    <foo>
        <main_title>this is another main title</main_title>
            <listings>
               <a_listing>
                  <sub_title>this is another sub title</sub_title>
                     <info name = "Dave" />
               </a_listing>
             </listings>
        </foo>

</xml>

Я хочу иметь возможность сгладить эту структуру, чтобы она выглядела примерно так

this is a main title | this is a sub title | bob 
this is a main title | this is a sub title | Ann
this is a main title |  this is a different sub title | Peter 
this is a main title |  this is a different sub title | Steve
this is another main title | this is another sub title | Dave

Я сейчас использую Beautifulsoup.

У меня так далеко

parse = soup.foo.children

for i in parse:
    print(i)

я в этом случае дам мне кусок XML. Я изо всех сил пытаюсь попасть в отдельные разделы, чтобы сгладить данные по мере необходимости

Любая помощь будет принята с благодарностью! Спасибо

1 Ответ

0 голосов
/ 06 сентября 2018

Попробуйте это

from bs4 import BeautifulSoup

file = open('./test.xml')
data = "\n".join(file.readlines())

soup = BeautifulSoup(data, "lxml")

titles = soup.find_all('main_title')

for title in titles:
    lsts = title.parent.find_all('a_listing')

    for lst in lsts:
        infos = lst.find_all('info')

        for info in infos:
            print(f"{title.text} | {lst.sub_title.text} | {info['name']}")
...