-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetinputxml.py
79 lines (52 loc) · 2.03 KB
/
setinputxml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from lxml import etree
"""
# Example of use:
from lxml import etree
inputtree = etree.parse("input.xml")
xpath = "/input/groundstate/@nempty"
value = 5
setinputxml.setByXpath(inputtree,xpath,value)
inputtree.write("input.xml",pretty_print="true")
# Another example of use:
from lxml import etree
inputtree = etree.parse("input.xml")
xpath = "/input/keywords" # or equivalently "/input/keywords[1]"
value = "Keywords for the run"
setinputxml.setByXpath(inputtree,xpath,value)
inputtree.write("input.xml",pretty_print="true")
# Example of xpath to change the third basevect of the crystal structure definition:
from lxml import etree
inputtree = etree.parse("input.xml")
xpath = "/input/structure/crystal/basevect[3]" # or equivalently "/input/keywords[1]"
value = "Keywords for the run"
setinputxml.setByXpath(inputtree,xpath,value)
inputtree.write("input.xml",pretty_print="true")
"""
def setByXpath(inputtree,xpath,value):
if "@" in xpath:
element = xpath.split("/@")[0]
attrib = xpath.split("/@")[1]
inputtree.xpath(element)[0].attrib[attrib]=value
else:
if "][" in xpath:
# In this case, the xpath could be something like
# /input/structure/crystal/basevect[3][3]
# where we want to address the third component of the third basevect vector.
basexpath = xpath.split("][")[-2]+"]"
oldtext = inputtree.xpath(basexpath)[0].text
stext = oldtext.split()
component = int(xpath.split("][")[1][:-1])
stext[component-1] = str(value)
newtext = " ".join(stext)
inputtree.xpath(basexpath)[0].text = newtext
else:
inputtree.xpath(xpath)[0].text = value
"""
# Just for testing purposes
inputtree = etree.parse("/home1/srigamonti/projects/cobalt_bulk/runs/1345479936227/input.xml")
xpath = "/input/structure/crystal/basevect[3][3]"
value = "Keywords for the run"
setByXpath(inputtree,xpath,value)
#inputtree.write("input.xml",pretty_print="true")
print etree.tostring(inputtree)
"""