用python替换xml中的树元素
问题描述:
#!/usr/bin/env python
import libxml2
import os.path
from cfs_utils import *
solvers = ["CG","CGS","BICGSTABL"]
precond = ["saamg","iluk","ssor"]
for s in range(3):
for p in range(3):
print "s " + str(s)
problem = "eval_" + str(solvers[s]) + "_" + str(precond[p]) + "_default"
#if os.path.exists(problem + ".info.xml"):
# continue
print "execute " + problem + "\n"
doc = libxml2.parseFile("simp_lis_solver_3D.xml")
xml = doc.xpathNewContext()
solver = xml.xpathEval('//solverList')
xml.setContextNode(solvers)
solver_name = xml.xpathEval(solvers[s])
这里我想用指定的求解器名称替换xml元素,我尝试用下面的方式在下面进行人工合成,但没有任何工作。用python替换xml中的树元素
#[0].getContent()
# xml.xpathRegisterNs('cfs', 'http://www.cfs++.org')
#replace(xml, "//cfs:volume/@value", str(vol))
# replace("pardiso", "CG", "CGS")
for line in doc:
solvers[s].replace('TFQMR', 'CG')
doc.saveFile(problem + ".xml")
execute("cfs.rel -m bulk3d_10.mesh " + problem)
下面是一个使用此XML文件,我想在我的Python代码指定的解算器,以取代求解TFGMR我的XML文件,这里的样品。
<system>
<solutionStrategy>
<standard>
<matrix storage="sparseNonSym"/>
</standard>
</solutionStrategy>
<solverList>
<lis id="default">
<precond><saamg/>
</precond>
<solver>
<TFQMR></TFQMR>
</solver>
<maxIter>10000</maxIter>
<tolerance>1.0E-10</tolerance>
<logging>false</logging>
</lis>
</solverList>
</system>
</linearSystems>
答
您可以从父去除,然后更换使用xml.ElementTree:
from xml.etree import ElementTree as et
tree = et.parse("your.xml")
x = tree.getroot()
for s in x.findall(".//solver"):
ch = s.find("./TFQMR")
if ch is not None:
s.remove(ch)
s.append(et.SubElement(s, "CG"))
print(et.tostring(x))
使用您的片段:
In [55]: from xml.etree import ElementTree as et
In [56]: tree = et.parse("test.xml")
In [57]: x = tree.getroot()
In [58]: for s in x.findall(".//solver"):
....: ch = s.find("./TFQMR")
....: if ch is not None:
....: s.remove(ch)
....: s.append(et.SubElement(s, "CG"))
....:print(et.tostring(x))
....:
<system>
<solutionStrategy>
<standard>
<matrix storage="sparseNonSym" />
</standard>
</solutionStrategy>
<solverList>
<lis id="default">
<precond>
<saamg />
</precond>
<solver>
<CG /><CG /></solver>
<maxIter>10000</maxIter>
<tolerance>1.0E-10</tolerance>
<logging>false</logging>
</lis>
</solverList>
</system>
使用你的文件,你需要注册命名空间:
from xml.etree import ElementTree as et
tree = et.parse(.xml")
x = tree.getroot()
namespaces = {'cfsSimulation': "http://www.cfs++.org"}
solvers = x.findall(
"cfsSimulation:sequenceStep/cfsSimulation:linearSystems/cfsSimulation:system"
"//cfsSimulation:solverList/cfsSimulation:lis/cfsSimulation:solver",namespaces)
for s in solvers:
ch = s.find("./cfsSimulation:TFQMR", namespaces)
if ch is not None:
s.remove(ch)
s.append(et.SubElement(s, "CG"))
print(et.tostring(x))
请编辑你的问题,并包括一个XML的样本。 – 2016-05-12 10:54:23
你有lxml吗? –
没有只是xml文件 – Nithish