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: ?

Maddy Chavda
  • 591
  • 6
  • 10
  • 20
  • `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` .. – har07 Dec 30 '16 at 13:06
  • Let me try with lxml. Thanks – Maddy Chavda Dec 30 '16 at 14:03
  • Two related, unanswered questions: http://stackoverflow.com/q/38663191/407651, http://stackoverflow.com/q/38438921/407651 – mzjn Dec 30 '16 at 22:04

0 Answers0