I am finding elements from XML1 in XML2 and after that i want to insert one comment XML1 is:
<Price>
<Amount>100</Amount>
<Amount>102</Amount>
<Amount>103</Amount>
</Price>
and XML2 is:
<List>
<Item>
<Price>
<Amount>100</Amount>
<Next_Item>
<Name>Apple</Name>
</Next_Item>
<Next_Item>
<Name>Orange</Name>
</Next_Item>
</Price>
<Price>
<Amount>200</Amount>
<Next_Item>
<Name>Apple</Name>
</Next_Item>
<Next_Item>
<Name>Orange</Name>
</Next_Item>
</Price>
</Item>
</List>
Output XML i want is following where I want to insert a comment above Price if the value is matching from price/amount from XML2:
<List>
<Item>
<!--important-->
<Price>
<Amount>100</Amount>
<Next_Item>
<Name>Apple</Name>
</Next_Item>
<Next_Item>
<Name>Orange</Name>
</Next_Item>
</Price>
<Price>
<Amount>200</Amount>
<Next_Item>
<Name>Apple</Name>
</Next_Item>
<Next_Item>
<Name>Orange</Name>
</Next_Item>
</Price>
</Item>
</List>
After getting help from this forum I tried coding like this:
xml1 = etree.parse('C:/Python/XML1.xml')
xml2 = etree.parse('C:/Python/XML2.xml')
for am in xml1.xpath('//Price/Id/text()'):
x = xml2.xpath(f'//List/Item/Price[./Amount/text()="{am}"]')
if len(x)>0:
root = xml2.find('.//List/Item/Price')
root.insert(1, etree.Comment('important'))
etree.dump(root)
with open('C:/Python/output.xml','w') as f:
f.write(etree.Comment(root))
I am not able to get proper output xml I am getting error: AttributeError: 'NoneType' object has no attribute 'insert'
Grateful for any kind of help.