rj487
rj487

Reputation: 4634

Python add new element by xml ElementTree

XML file

<?xml version="1.0" encoding="utf-8"?>
<Info xmlns="BuildTest">
<RequestDate>5/4/2020 12:27:46 AM</RequestDate>
</Info>

I want to add a new element inside the Info tag.

Here is what I did.

import xml.etree.ElementTree as ET

tree = ET.parse('example.xml')
root = tree.getroot()
ele = ET.Element('element1')
ele.text = 'ele1'
root.append(ele)
tree.write("output.xhtml")

Output

<ns0:Info xmlns:ns0="BuildTest">
<ns0:RequestDate>5/4/2020 12:27:46 AM</ns0:RequestDate>
<element1>ele1</element1></ns0:Info>

Three questions:

  1. The <?xml version="1.0" encoding="utf-8"?> is missing.
  2. The namespace is wrong.
  3. The whitespace of the new element is gone.

I saw many questions related to this topic, most of them are suggesting other packages. Is there any way it can handle properly?

Upvotes: 1

Views: 166

Answers (1)

Amitai Irron
Amitai Irron

Reputation: 2055

The processing instructions are not considered XML elements. Just Google are processing instructions part of an XML, and the first result states:

Processing instructions are markup, but they're not elements.

Since the package you are using is literally called ElementTree, you can reasonably expect its objects to be a trees of elements. If I remember correctly, DOM compliant XML packages can support non-element markup in XML.

For the namespace issue, the answer is in stack overflow, at Remove ns0 from XML - you just have to register the namespace you specified in the top element of your document. The following worked for me:

ET.register_namespace("", "Buildtest")

As for the whitespace - the new element does not have any whitespace. You can assign to the tail member to add a linefeed after an element.

Upvotes: 1

Related Questions