0

I have the following XML

<Head>
<child></child>
</Head>

And I want to alter the XML to something like this:

<Parent>
<child></child>
</Parent>

How do I do this? I have read this and this but they use Element tree.

3
  • 1
    What is lxml2? Do you mean lxml or perhaps the libxml2 Python bindings? Commented Jan 19, 2015 at 11:29
  • I am sorry, updated the question tag. Commented Jan 19, 2015 at 11:35
  • If my answer solves this problem, don't forget to accept it. :) Commented Jan 23, 2015 at 6:08

1 Answer 1

1

For instance, you have this original file.

<Head>
<child>this is text for child</child>
</Head>

Then you can use xml.dom.minidom to change name of root tag.

#-*- coding:utf-8 -*-
#!/usr/bin/env python


import xml.dom.minidom

info = '''
<Head>
<child>this is text for child</child>
</Head>
'''

dom = xml.dom.minidom.parseString(info)
dom.firstChild.tagName = 'parent'
# save it to any file you want
xml_file = 'C:\\temp\\lch.xml'
f = open(xml_file, 'wb')
dom.writexml(f)
f.close()

OUTPUT:

<?xml version="1.0" ?><parent>
<child>this is text for child</child>
</parent>
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.