View difference between Paste ID: k4XsHCkR and 0x6WNHmF
SHOW: | | - or go back to the newest paste.
1-
import pandas as pd
1+
## for https://stackoverflow.com/q/74567311/6146136
2
#### links to outputs:
3-
from lxml import etree as Etr
3+
###### studentinfo_output.xml at https://pastebin.com/bPFg8TBL
4-
#import ElementTree
4+
###### studentinfo_op_unpretty.xml at https://pastebin.com/6NgFsYU0
5-
from xml.etree import ElementTree as ET
5+
###### studentinfo_op_regpretty.xml at https://pastebin.com/5FQxLzCC
6-
from xml.parsers import expat
6+
7-
from bs4 import BeautifulSoup
7+
8-
import pandas_read_xml as pdx
8+
from bs4 import BeautifulSoup 
9
10-
with open('studentinfo.xml', 'r') as f:
10+
with open('studentinfo.xml', 'r') as f: 
11-
    file = f.read()
11+
    xhtml = f.read() # [I just don't like "file" as a variable name]
12-
soup = BeautifulSoup(file, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces
12+
soup = BeautifulSoup(xhtml, 'lxml') ##  'xml' parser ---> lose namespaces
13
 
14
enumTags = ['st:name']
15
for d in [c for c in soup.descendants if c.name]:
16
    for name in enumTags:
17
        for i, t in enumerate(d.find_all(name, recursive=False)):
18
            t.name = f'{t.name}{i}'
19-
            print(soup.prettify)
19+
20-
    
20+
            # print(soup.prettify) 
21
            # prettify is a method so it should be prettify()
22
            # if you print inside loop, it'll print with every edit
23
24
# to save the new xml [3 different options]
25
with open('studentinfo_output.xml', 'wb') as f: 
26
    f.write(soup.prettify('utf-8')) # option 1
27
with open('studentinfo_op_unpretty.xml', 'wb') as f: 
28
    f.write(str(soup).encode('utf-8')) # option 2
29
30
import re
31
rpx = re.sub('[^> ]\s*\n\s*<', '<', soup.prettify())
32
rpx = re.sub('>\s*\n\s*[^< ]', '>', rpx)
33
with open('studentinfo_op_regpretty.xml', 'wb') as f: 
34
    f.write(rpx.encode('utf-8')) # option 3
35