2

I have an xml file as follows in which i want to add one more tag with attributes inside it using a python script.

<package> 
  <data> 
    <id>sample</id> 
    <version>1.1</version> 
  </data>
  <files>
   <file src = "C:/sample.txt"/>
  </files>
</package>

The python script with which i am adding the tag with attribute is as follows script but its not adding the tag as i desire:

import xml.etree.ElementTree as ET
tree_A = ET.parse('test.xml')
root_A= tree_A.getroot()
print root_A[1].tag
if root_A[1].tag is not None:    
    newNodeName = ET.Element('file src')
    newNodeName.text ="D:/other.txt"
    newNode.append(newNodeName)
    root_A[1].insert(0,newNodeName)
tree_A.write('test.xml')

and the output xml i am getting is:

<package> 
  <data> 
    <id>sample</id> 
    <version>1.1</version> 
  </data>
  <files>
   <file src = "C:/sample.txt"/>
   ###i want following tag as <file src ="D:/other.txt"/>
   <file src> D:/other.txt</file src> 
  </files>
</package>

So, please suggest how can i have a tag with attribute being added in xml file?

1 Answer 1

1

You can use ET.Element('file', {'src':'D:/other.txt'}) to construct the element named file with an attribute named src.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.