Issue
I am working on parsing an .xml
file. I need to convert to a .csv
Person file: names.txt
.
e.g.:
names.txt
:
anna
james
miray
vill
XML file:
<data>
<AAA>
<CCC>
<person>name1</person>
</CCC>
<CCC>
<person>name2</person>
</CCC>
<CCC>
<person>name3</person>
</CCC>
</AAA>
</data>
Solution
You can use this:
from bs4 import BeautifulSoup
example_string = '<data><AAA><CCC><person>name1</person></CCC><CCC><person>name2</person></CCC><CCC><person>name3</person></CCC></AAA></data>'
# Here I hard code the list of names. My assumption is you already know how
# to read the names from names.txt into a list.
names = ['anna', 'james', 'miray']
# Parse the XML into a BeautifulSoup
soup = BeautifulSoup(example_string, 'lxml-xml')
# Replace the content of each 'person' tag
for name, item in zip(names, soup.find_all('person')):
item.string = name
# Pretty-print the XML after modifications
print(soup.prettify())
This will have the following output:
<?xml version="1.0" encoding="utf-8"?>
<data>
<AAA>
<CCC>
<person>
anna
</person>
</CCC>
<CCC>
<person>
james
</person>
</CCC>
<CCC>
<person>
miray
</person>
</CCC>
</AAA>
</data>
Answered By - Shane Bishop
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.