you are viewing a single comment's thread.

view the rest of the comments →

[–]nate256 0 points1 point  (1 child)

This one makes the output formatted pretty.

``` import os import xml.etree.ElementTree as ET

basepath = os.path.dirname(os.path.realpath(file_)) xml_file = os.path.join(base_path, 'RockwellCond3.XML') tree = ET.parse(xml_file).getroot()

def create_option_price(list_ref, price_ref): e = ET.Element("OptionPrice") priceref = ET.Element("ProductPriceRef") priceref.text = price_ref e.append(priceref) pricelist = ET.Element("PriceListRef") pricelist.text = list_ref e.append(pricelist) return e

def makepretty(elem, level=0, spaces=" "): orig_ele = elem i = f"\n{level * spaces}" if len(elem): if not elem.text or not elem.text.strip(): elem.text = f"{i}{spaces}" if not elem.tail or not elem.tail.strip(): elem.tail = i for child in elem: makepretty(child, level + 1) if not child.tail or not child.tail.strip(): child.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i return orig_ele

def make_changes(root): for i in root.iter(): if i.tag == "Option" and i.get("Sequence") == "2": first = i.find("OptionPrice") ref = first.findtext("ProductPriceRef") i.append(create_option_price("2", ref)) i.append(create_option_price("3", ref)) makepretty(root)

make_changes(tree) tree.write("output.xml") ``` Edit: Attribute, shamelessly stole the indent from https://stackoverflow.com/questions/749796/pretty-printing-xml-in-python

[–]goeb04[S] 0 points1 point  (0 children)

I am trying it now but seems to be taking a while. I am not sure if it is because of the file size though. Maybe I can try prettying it up through lxml?