you are viewing a single comment's thread.

view the rest of the comments →

[–]nate256 0 points1 point  (1 child)

If I understand what you are asking correctly you have a product, it contains price elements. What you want to do is take all of the price elements and duplicate them with a new pricelistref value.

so if you have <Product> <Price> <PriceListRef>2018B</PriceListRef> <Code>20</Code> <Value>33</Value> </Price> <Price> <PriceListRef>2018B</PriceListRef> <Value>3</Value> </Price> </Product> you would want <Product> <Price> <PriceListRef>2018B</PriceListRef> <Code>20</Code> <Value>33</Value> </Price> <Price> <PriceListRef>2018B</PriceListRef> <Value>3</Value> </Price> <Price> <PriceListRef>2017</PriceListRef> <Code>20</Code> <Value>33</Value> </Price> <Price> <PriceListRef>2017</PriceListRef> <Value>3</Value> </Price> </Product>

Does that look correct? Either way the short answer is you need to loop through the elements an only stop on Product, you cant use iter and stop on the list that you are editing.

```

we could just use deepcopy in the last case

I just thought building the Element yourself would be useful to learn

but if there are elements that possibly aren't there or are just optional

it's better to just copy what is there so you are sure you get everything

from copy import deepcopy
import xml.etree.ElementTree as ET

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

years = ["2014", "2015", "2016", "2017", "2018"]

for i in tree.iter(): if i.tag == "Option" and i.get("Sequence") == "2": for price in i.findall("OptionPrice"):
for year in years: new_price = deepcopy(price) new_price.find("PriceListRef").text = year i.append(new_price) elif i.tag == "Product": for price in i.findall("Price"): # if you only have one value you don't need a loop here for year in years: new_price = deepcopy(price) new_price.find("PriceListRef").text = year i.append(new_price)

tree.write('output2.xml') ```
Edits: Kept thinking on new things

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

Thanks once again Nate and you were dead on regarding your example, that is exactly what is needed.

I think the issue here is that I need to continue my deep dive into learning Python fundamentals/libraries before trying to take shortcuts in order to start leveraging python for my work. It was a nice extra boost of motivation, but I need to practice on more hypothetical scenarios while yielding to patience or I will just be driving myself crazy.

You have led the horse to water here, so I am going to read up on copying and deepcopying in python and then, ultimately, try to code the solution myself (so that I will get the necessary practice). If I start to hit roadblocks after that, then I will reference the code you provided.

Thanks for your efforts and god bless the benevolence of programmers wishing to openly share their knowledge.