maximus
maximus

Reputation: 99

How to create a XML template?

i have 2 Python scripts that write to a same XML file. i'm using Python2.5 and WinXP. How can I create a template so that the XML file isn't overwritten when I run another Python script. It will only updates the section in the XML with value. For eg:XML template as below:

<Test>
 <Default>
   <Value>1</Value> 
   <Link_Status>0</Link_Status> 
   <Lane_Status>1</Lane_Status> 
 </Default>
 <Settings>
  <Point>4</Point> 
  <Delay>1</Delay> 
 </Settings>
</Test>

i want default.py to update to the Default section and Settings.py to update the Settings section. appreciate your advice. tq

Default.py code:

import elementtree.ElementTree as ET 

root=ET.Element("Test")
head1=ET.SubElement(root,"Default")
title=ET.SubElement(head1,"Value")
title.text="1"

title=ET.SubElement(head1,"Link_Status")
title.text="0"

title=ET.SubElement(head1,"Lane_Status")
title.text="1"

tree=ET.ElementTree(root)
tree.write("C:\Python25\myscript\cmm\\config.xml")

Settings.py code:

import elementtree.ElementTree as ET

root=ET.Element("Test")
head2=ET.SubElement(root,"Settings")
title=ET.SubElement(head2,"Point")
title.text=("4")

title=ET.SubElement(head2,"Delay")
title.text=("1")

tree=ET.ElementTree(root)
tree.write("C:\Python25\myscript\cmm\\config.xml")

Upvotes: 1

Views: 3615

Answers (1)

winterTTr
winterTTr

Reputation: 1768

Read and just update the specific section instead of the whole file, like below

from xml.etree import ElementTree as ET
with open("test.xml") as f:
    root = ET.parse( f ).getroot()

# update <Default>
root.remove( root.find("./Default") )

defaultNode = ET.SubElement(root,"Default")
ET.SubElement(defaultNode,"Value").text = "999"
ET.SubElement(defaultNode,"Link_Status").text = "888"
ET.SubElement(defaultNode,"Lane_Status").text = "777"

with open("test.xml" , "w" ) as f:
    f.write( ET.tostring( root ) )

----EDIT TO ADD NEW--

Actually, I just want to show you the way that you can just read in the file and update some section and then write them out without have to create a new xml content every time. OK, if your xml structure is static, you can just update the specific text by locating it with XPATH, maybe the following one can solve your little issues.

from xml.etree import ElementTree as ET
with open("test.xml") as f:
root = ET.parse( f ).getroot()

# update <Default>
root.find("./Default/Value").text = "999"
root.find("./Default/Link_Status").text = "888"
root.find("./Default/Lane_Status").text = "777"

with open("test.xml" , "w" ) as f:
    f.write( ET.tostring( root ) )

BTW,
As regards to the first example, if I do not remove the before adding a new one, you will get two node under , that's is why I use remove firstly to remove the old one and create a new one.

Upvotes: 1

Related Questions