1

I am trying to convert xml to string and string to xml.

Input xml file:

<?xml version="1.0"?>
<records>
        <record id="1">
                <url>https://www.google.com</url>
                <data>
                        <a xmlns="http://localhost:8080/">
                                <b>1</b>
                                <c>Mayur</c>
                        </a>
                </data>
        </record>
        <record id="2">
                <url>https://www.google.com</url>
                <data>
                        <a xmlns="http://localhost:8080/">
                                <b>2</b>
                                <c>chavda</c>
                        </a>
                </data>
        </record>
</records>

I can't get same xml file when i convert string to xml

tree = ET.parse(xmlfilepath)
root = tree.getroot()
print (tree.tostring(root))

xmlnx moved to records tag.

<records xmlns:ns0="http://localhost:8080/">
            <record id="1">
                    <url>https://www.google.com</url>
                    <data>
                            <ns0:a>
                                    <ns0:b>1</ns0:b>
                                    <ns0:c>Mayur</ns0:c>
                            </ns0:a>
                    </data>
            </record>
            <record id="2">
                    <url>https://www.google.com</url>
                    <data>
                            <ns0:a>
                                    <ns0:b>2</ns0:b>
                                    <ns0:c>chavda</ns0:c>
                            </ns0:a>
                    </data>
            </record>
    </records>

Can i get same xml as output which i have given as a input? What is the reason for changing xml attribute and adding ns0:, ns1: ?

3
  • tree.tostring(root) didn't work. Maybe you meant ET.tostring(root)? Anyway this seems to be a buggy behavior of xml.etree.ElementTree. The same didn't happen using lxml.etree.ElementTree .. Commented Dec 30, 2016 at 13:06
  • Let me try with lxml. Thanks Commented Dec 30, 2016 at 14:03
  • Two related, unanswered questions: stackoverflow.com/q/38663191/407651, stackoverflow.com/q/38438921/407651 Commented Dec 30, 2016 at 22:04

0

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.