(Dec-15-2018, 01:18 PM)yuyu Wrote: Is this somehow possible for the following example to read Name, Age and Number and write it to a new file?
Yes of course,you should try yourself
It's not so common to parse a whole XML file to text with tags names.
Use
BBCode code tag,and a XML file usually have have indentation then is easier to the see structure.
Example:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<friends>
<human>
<Name>Tim</Name>
<Age>23</Age>
<Number>1234</Number>
</human>
<human>
<Name>Jenny</Name>
<Age>23</Age>
<Number>4321</Number>
</human>
<animal>
<Name>Wuff</Name>
<Age>4</Age>
<Number>2323</Number>
</animal>
</friends>
</data>
So it a read this file and do some test.
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('test.xml'), 'lxml')
Test:
>>> for tag in soup.find_all('human'):
... for item in tag.find_all(['name', 'age', 'number']):
... print(item)
...
<name>Tim</name>
<age>23</age>
<number>1234</number>
<name>Jenny</name>
<age>23</age>
<number>4321</number>
This get all under human,so if use
friends
will get both human/animal.
>>> for tag in soup.find_all('friends'):
... for item in tag.find_all(['name', 'age', 'number']):
... print(item)
...
<name>Tim</name>
<age>23</age>
<number>1234</number>
<name>Jenny</name>
<age>23</age>
<number>4321</number>
<name>Wuff</name>
<age>4</age>
<number>2323</number>
So can look like this,write to file you can try yourself.
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('test.xml'), 'lxml')
for tag in soup.find_all('friends'):
for item in tag.find_all(['name', 'age', 'number']):
print(f'{item.name.capitalize()}:{item.text}')
Output:
Name:Tim
Age:23
Number:1234
Name:Jenny
Age:23
Number:4321
Name:Wuff
Age:4
Number:2323