DECROMAX

Parse xml to list of dict

May 11th, 2022
1,196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. from bs4 import BeautifulSoup
  2.  
  3. def parse_xml(series: pd.Series) -> list:
  4.     """Input: xml, Returns list of dict"""
  5.  
  6.     xml = series.replace('">', '">\n')
  7.     soup = BeautifulSoup(xml, features="xml")
  8.    
  9.     # returns list of all items within node
  10.     values = [i.text.split("\n") for i in soup.find_all("node")] # replace "node" with relevent one
  11.  
  12.     stack = []
  13.     for lst in values:
  14.         items = {
  15.             "item": lst[1],  # change to keys and index to suit
  16.             "length": lst[2],
  17.             "width": lst[3],
  18.             "height": lst[4],
  19.             "quantity": lst[5],
  20.             "height_band": lst[6],
  21.             "eng_factor": lst[7],
  22.             "m2_calc": lst[9]
  23.         }
  24.         stack.append(items)
  25.     return stack
  26.  
  27. # how to apply to series
  28. df["parsed_xml"] = df["parsed_xml"].apply(parse_xml)
Advertisement
Add Comment
Please, Sign In to add comment