0

I am trying to merge multiple xml files into one. I have come across multiple previously answered similar solutions. However, I have not found one that fits my problem. I have 3 xml files with different attributes. One of the xml files has a <main1></main>.I am trying to grab the content of the other xml files and place it inside this tag along with the existing data.

test1.xml

<acura>
    <Brand>Acura</Brand>
    <Model>NSX 2017</Model>
    <Price>156000</Price>
</acura>

file2.xml

<honda>
    <Brand>Honda</Brand>
    <Model>Accord</Model>
    <Price>24</Price>
</honda>

something3.xml

<main>
<bmw>
    <Brand>BMW</Brand>
    <Model>5 Series</Model>
    <Price>51200</Price>
</bwm>
</main>
7
  • Do you have already any code or do you want to someone write it for you? If you have, pls show it, otherwise I am not sure that anyone would write a code. If it is not required to use elementtree, I have similar code, which I can adopt to your needs. Commented Mar 3, 2017 at 17:16
  • The data in files(cars) always are different? Is possible duplicates? Commented Mar 3, 2017 at 17:25
  • @TitanFighter I been trying to work of this code here but no luck Commented Mar 3, 2017 at 17:39
  • @DanilaGanchar Sorry, I updated the tags accordingly Commented Mar 3, 2017 at 17:40
  • 1
    @MaryCoding add please some source what are you tried. Commented Mar 3, 2017 at 17:58

1 Answer 1

1

The main thing you might need to know about is insert.

Parse each of the files and then, use Brand to navigate to the car's marque as parent or grandparent. Finally insert.

>>> import os
>>> os.chdir('c:/scratch')
>>> from lxml import etree
>>> test1 = etree.parse('test1.xml')
>>> file2 = etree.parse('file2.xml')
>>> something3 = etree.parse('something3.xml')
>>> acura = test1.find('Brand').getparent()
>>> acura
<Element acura at 0xa27388>
>>> honda = file2.find('Brand').getparent()
>>> main = something3.xpath('.//Brand')[0].getparent().getparent()
>>> main.insert(0, acura)
>>> main.insert(0, honda)
>>> str = etree.tostring(main, pretty_print=True)
>>> str
b'<main>\n<honda>\n    <Brand>Honda</Brand>\n    <Model>Accord</Model>\n    <Price>24</Price>\n</honda><acura>\n    <Brand>Acura</Brand>\n    <Model>NSX 2017</Model>\n    <Price>156000</Price>\n</acura><bmw>\n    <Brand>BMW</Brand>\n    <Model>5 Series</Model>\n    <Price>51200</Price>\n</bmw>\n</main>\n'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.