1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The XML declaration is a special kind of processing instruction that is easily added. Just use tree.write("output.xhtml", xml_declaration=True, encoding="utf-8").
@mzjn - thanks, I learned something new. I never bothered with processing instructions, as all my XML usage was always in case where my programs were both the producers and consumers of the XMLs.

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.