XML header getting removed after processing with elementtree

2024/9/20 20:11:04

i have an xml file and i used Elementtree to add a new tag to the xml file.My xml file before processing is as follows

<?xml version="1.0" encoding="utf-8"?><PackageInfo xmlns="http://someurlpackage"><data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
</PackageInfo>

I used following python code to add a new data tag and write it to my xml file

 tree = ET.ElementTree(xmlFile)root = tree.getroot()elem= ET.Element('data')elem.attrib['ID']="http://someurldata4"elem.text='data4'root[1].append(elem)tree = ET.ElementTree(root)tree.write(xmlFile)

But the resultant xml file have <?xml version="1.0" encoding="utf-8"?> absent and the file looks as below

<PackageInfo xmlns="http://someurlpackage">
<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
</PackageInfo>

Is there any way to include the xml header rather than hardcoding the line

Answer

It looks like you need optional arguments to the write method to output the declaration.

http://docs.python.org/library/xml.etree.elementtree.html#elementtree-elementtree-objects

tree.write(xmlfile,xml_declaration=True)

I'm afraid I'm not that familiar with xml.etree.ElementTree and it's variation between python releases.

Here's it working with lxml.etree:

>>> from lxml import etree
>>> sample = """<?xml version="1.0" encoding="utf-8"?>
... <PackageInfo xmlns="http://someurlpackage">
... <data ID="http://someurldata1">data1</data >
... <data ID="http://someurldata2">data2</data >
... <data ID="http://someurldata3">data3</data >
... </PackageInfo>"""
>>>
>>> doc = etree.XML(sample)
>>> data = doc.makeelement("data")
>>> data.attrib['ID'] = 'http://someurldata4'
>>> data.text = 'data4'
>>> doc.append(data)
>>> etree.tostring(doc,xml_declaration=True)
'<?xml version=\'1.0\' encoding=\'ASCII\'?>\n<PackageInfo xmlns="http://someurlpackage">\n<data ID="http://someurldata1">data1</data>\n<data ID="http://someurldata2">data2</data>\n<data ID="http://someurldata3">data3</data>\n<data ID="http://someurldata4">data4</data></PackageInfo>'
>>> etree.tostring(doc,xml_declaration=True,encoding='utf-8')
'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<PackageInfo xmlns="http://someurlpackage">\n<data ID="http://someurldata1">data1</data>\n<data ID="http://someurldata2">data2</data>\n<data ID="http://someurldata3">data3</data>\n<data ID="http://someurldata4">data4</data></PackageInfo>'
https://en.xdnf.cn/q/72074.html

Related Q&A

How to ntp server time down to millisecond precision using Python ntplib?

I am creating a python module that will output the time from a selection of NTP Pool servers to millisecond precision as an exercise in showing how server timestamps vary. Thus far I have been able to …

Control 2 separate Excel instances by COM independently... can it be done?

Ive got a legacy application which is implemented in a number of Excel workbooks. Its not something that I have the authority to re-implement, however another application that I do maintain does need t…

nested Python numpy arrays dimension confusion

Suppose I have a numpy array c constructed as follows:a = np.zeros((2,4)) b = np.zeros((2,8)) c = np.array([a,b])I would have expected c.shape to be (2,1) or (2,) but instead it is (2,2). Additionally,…

how to reuse tests written using unittest.testcase

Ive written some tests using unittest as below and I want to reuse them in another class where Im stuck and need help.. Code snippets are as below.MyTestClass.pyClass MyTestClass(unittest.TestCase): …

Randomized stratified k-fold cross-validation in scikit-learn?

Is there any built-in way to get scikit-learn to perform shuffled stratified k-fold cross-validation? This is one of the most common CV methods, and I am surprised I couldnt find a built-in method to …

Find all paths through a tree (nested dicts) from top to bottom

EDIT: See below for a suggested answer and how its not quite right yet.There are many similar questions to this one on Stack Overflow, but none exactly like it in Python. Im a programming novice, so pl…

How to show process state (blocking, non-blocking) in Linux

Is there a way to query the state of processes in a Linux process table to be able to demonstrate if a process is running or blocked at the time the query is executed? My goal is to do this from outsi…

Removing quotation marks from list items

I am running this program:f = open( "animals.txt", "r") g = f.read() g1 = g.split(,) #turning the file into list print g1And I want this to come out:[ELDEN, DORSEY, DARELL, BRODERIC…

Handle multiple questions for Telegram bot in python

Im programming a telegram bot in Python using the Telegram bot API. Im facing the problem of managing questions that need an answer of the user. The problem arises when the program is waiting for an an…

Which GTK+ elements support which CSS properties?

While applying my own CSS to my GTK+ application, I noticed, that some elements ignore some CSS properties and others ignore others or dont ignore them, which leads me to search for an overview of whic…