0
votes

I have a text files in a one directory like "Rest.txt", "Test.txt". Sample string in a txt file as shown below.

Input: <Hello> <Message><stdout>"weblogic.servelt.Default(self-tuning)"] <12-18-2020> <?xml version="1.0" encoding="UTF-8"?><breakfast_menu><food><name>Belgian Waffles</name><price>$5.95</price> <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description><calories>650</calories></food><food><name>Strawberry Belgian Waffles</name> <price>$7.95</price><hello><sjiadasjhds>954jkldfksfkfjsdfklsdjf

In between the above given string there has XML tags. I need to extract all XML tags and save it in another directory using python. Like this I need to extract all XML data in all text files and save it.

Output :

<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price> 
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description><calories>650</calories>
</food>
</breakfast_menu>```
1
You can use BeautifulSoup as 'xml' parser and get all 'breakfast_menu' you will get what you need - Aakash aggarwal
Thanks for your comment. In my path directory the output of multiple a log string files will have different xml tags with not only starting with <breakfast_menu> there might be a different tags also. Could you please confirm how to loop all files and extract and save it in another directory as a xml file using Python - sai
you can use lxml etree to get the tags. Using this you can get all the tags and then you can find them using bs4 - Aakash aggarwal

1 Answers

0
votes

You can extract the tag using this code

from bs4 import BeautifulSoup
a = open("test.txt","r").read()
soup = BeautifulSoup(a, 'xml')
result = soup.find("breakfast_menu")

the result is what you need now you can write it in a file you want