本文整理汇总了Python中xml.etree.ElementTree.getroot方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.getroot方法的具体用法?Python ElementTree.getroot怎么用?Python ElementTree.getroot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.getroot方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gatherTimes
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def gatherTimes(filename,dataDir='.',addname="_complete", tCount=None):
"""
in case archiving failed to collect results from all times
"""
import h5py
xmlFile = open(filename+".xmf","r")
h5File = h5py.File(filename+".h5","r")
tree = ElementTree(file=xmlFile)
xmlFile.close()
XDMF = tree.getroot()
Domain = XDMF[0]
for TemporalGridCollection in Domain:
if tCount == -1:
SpatialCollection = TemporalGridCollection[-1]
Grids = SpatialCollection[:]
tCount = int(Grids[0].attrib['Name'])+1
del TemporalGridCollection[:]
for i in range(tCount):
dataset_name = TemporalGridCollection.attrib['Name']+"_"+`i`
dataset_name = dataset_name.replace(" ","_")
grid_array = h5File["/"+dataset_name]
size = grid_array.shape[0]
SpatialCollection=SubElement(TemporalGridCollection,"Grid",{"GridType":"Collection",
"CollectionType":"Spatial"})
time = SubElement(SpatialCollection,"Time",{"Value":grid_array.attrs['Time'],"Name":str(i)})
for j in range(size):
Grid = fromstring(grid_array[j])
SpatialCollection.append(Grid)
xmlFile = open(filename+addname+".xmf","w")
indentXML(tree.getroot())
tree.write(xmlFile)
xmlFile.close()
示例2: gatherXDMFfilesOpt
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def gatherXDMFfilesOpt(size,filename,dataDir='.',addname="_all",nStepsOnly=None,stride=1):
"""
in case archiving failed to collect results from various processors in parallel simulation
size -- nprocessors
"""
xmlFile = open(filename+str(0)+".xmf","r")
tree = ElementTree(file=xmlFile)
xmlFile.close()
nSteps = len(tree.getroot()[-1][-1])
if nStepsOnly != None:
nSteps = nStepsOnly
print "nSteps",nSteps
#stepsToGather=[i*stride for i in range(nSteps/stride)]
stepsToGather = range(0,nSteps,stride)
fAll = open(os.path.join(dataDir,filename+addname+str(size)+".xmf"),"w")
fAll.write(r"""<?xml version="1.0" ?>
<!DOCTYPE Xdmf SYSTEM "Xdmf.dtd" []>
<Xdmf Version="2.0" xmlns:xi="http://www.w3.org/2001/XInclude">
<Domain>
<Grid CollectionType="Temporal" GridType="Collection" Name="Mesh Spatial_Domain">
""")
for tn in stepsToGather:
print "time step",tn
print "subdomain",0
fAll.write(r""" <Grid CollectionType="Spatial" GridType="Collection">
""")
xmlFile = open(os.path.join(dataDir,filename+str(0)+".xmf"),"r")
tree = ElementTree(file=xmlFile)
xmlFile.close()
Grid=tree.getroot()[-1][-1][tn]
fAll.write(tostring(Grid[0]))
del Grid[0]
fAll.write(tostring(Grid))
for i in range(1,size):
print "subdomain",i
xmlFile = open(os.path.join(dataDir,filename+str(i)+".xmf"),"r")
tree = ElementTree(file=xmlFile)
xmlFile.close()
Grid=tree.getroot()[-1][-1][tn]
del Grid[0]
fAll.write(tostring(Grid))
fAll.write(r""" </Grid>
""")
fAll.write(r""" </Grid>
</Domain>
</Xdmf>
""")
fAll.close()
示例3: makeXML
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def makeXML(self, work_directory):
# </Artifact>
TheArtifact = Element( 'Artifact')
TheArtifact.attrib['xmlns']="http://geni.net/schema"
TheArtifact.attrib['xmlns:xsi']="http://www.w3.org/2001/XMLSchema-instance"
TheArtifact.attrib['xsi:schemaLocation']="http://geni.net/schema GENIObject.xsd"
# <Artifact><Type/>
Type = SubElement( TheArtifact, 'Type')
# <Artifact><Type><Primary/>
Primary = SubElement( Type, 'Primary')
Primary.text = self.art_type_prime
# <Artifact><Interpretation/>
Interpretation = SubElement( TheArtifact, 'Interpretation')
# <Artifact><Interpretation><Interpretation_read_me_text/>
Read_me_text = SubElement( Interpretation, 'Interpretation_read_me_text')
Read_me_text.text = self.interpretation_read_me
#To print to file
Test = ElementTree()
Test._setroot(TheArtifact)
root = Test.getroot()
self.indent(root)
Test.write(work_directory+'/artifact.xml')
示例4: update
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def update(self, xml_path):
file = open(xml_path)
try:
tree = ElementTree()
tree.parse(file)
finally:
file.close()
root = tree.getroot()
channel = root.find("channel")
conn = sqlite3.connect(self.path)
try:
cursor = conn.cursor()
for elem in channel.findall("item"):
record = TicketRecord()
record.parse(elem)
record.insert(cursor)
conn.commit()
finally:
conn.close()
示例5: dump
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def dump(elem):
if not isinstance(elem, ElementTree):
elem = ElementTree(elem)
elem.write(sys.stdout, encoding="unicode")
tail = elem.getroot().tail
if not tail or tail[-1] != "\n":
sys.stdout.write("\n")
示例6: getPitchRefListsOfTriadTypeFromFile
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def getPitchRefListsOfTriadTypeFromFile(filepath, triadType, musicXml, type="MusicXml"):
pitchLists = []
if type == "MusicXml":
fileBase = basename(filepath)
basenameIndex = filepath.index(fileBase)
harmonyFilePath = filepath[:basenameIndex] + "HM-" + basename(filepath)
ET = ElementTree()
ET.parse(harmonyFilePath)
regionXml = ET.getroot()
key = getKeyFromMusicXml(musicXml)
while regionXml:
for chord in regionXml.findall("chord-span"):
originalChordDegree = chord.attrib['deg']
print(originalChordDegree)
chordRootPitchClass = 0
curChordType = getTypeFromChordDegree(originalChordDegree, key)
pitchList = []
if curChordType == triadType:
for pitchRef in chord.findall("note"):
pitchRefId = pitchRef.attrib['id']
pitchList.append(pitchRefId)
pitchLists.append([originalChordDegree, pitchList])
regionXml = regionXml.find("region")
return pitchLists
示例7: convertTiddlyExport
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def convertTiddlyExport(inputFilepath, outputFilepath):
inTree = ElementTree()
inTree.parse(inputFilepath)
outTree = ElementTree(Element('entries'))
outRoot = outTree.getroot()
for item in inTree.getroot().findall('channel/item'):
newEntry = SubElement(outRoot, 'entry')
newEntryDate = SubElement(newEntry, 'date')
newDate = datetime.datetime.strptime(item.find('pubDate').text, tiddlyDateFormat)
newEntryDate.text = newDate.strftime(settings.DATE_FORMAT)
newEntryBody = SubElement(newEntry, 'body')
htmlText = item.find('description').text
bodyText = htmlText.replace('<br>', '\n');
bodyText = re.sub(r'\<.*?\>', "", bodyText)
newEntryBody.text = bodyText
outTree.write(outputFilepath)
示例8: do_PROPFIND
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def do_PROPFIND(self):
print 'PROPFIND ' + self.path
for key in self.headers.keys():
print key + '\t' + self.headers[key]
req = self.parseinputxml()
req = ElementTree(req)
res = ElementTree(Element(QName("DAV:", 'multistatus')))
self.addresponse('/', res.getroot(), 0)
self.writeresponse(res)
示例9: scan_dir
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def scan_dir(self, database, dir):
if not isinstance(dir, unicode):
dir = dir.decode(sys.getfilesystemencoding())
if not os.path.exists(dir):
print("does not exist")
return
dir = get_real_case(dir)
for name in os.listdir(dir):
if self.stop_check():
return
if name in [".git"]:
continue
path = os.path.join(dir, name)
if os.path.isdir(path):
self.scan_dir(database, path)
continue
dummy, ext = os.path.splitext(path)
ext = ext.lower()
#if ext not in self.extensions:
# continue
if ext != ".xml":
continue
self.scan_count += 1
self.set_status(
_("Scanning configurations ({count} scanned)").format(
count=self.scan_count), name)
print("scan", name)
result = None
try:
tree = ElementTree()
tree.parse(path)
root = tree.getroot()
if root.tag == "config":
result = self.scan_configuration(database, tree)
elif root.tag == "game":
self.scan_game(database, tree, path)
except Exception:
traceback.print_exc()
if result is not None:
if "name" in result:
name = result["name"]
else:
name, ext = os.path.splitext(name)
print("found", name)
search = self.create_configuration_search(name)
#name = self.create_configuration_name_from_path(path)
name = self.create_configuration_name(name)
database.add_configuration(path=path, uuid=result["uuid"],
name=name, scan=self.scan_version, search=search)
示例10: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
class ItemTree:
def __init__(self):
self.tree = ElementTree(file="data/sale.xml")
self.root = self.tree.getroot()
self.u_id = set()
for elem in self.root:
self.u_id.add(int(elem.get("uid")))
def getId(self):
id_itter = 1
while id_itter in self.u_id:
id_itter += 1
self.u_id.add(id_itter)
return id_itter
def remove_id(self, uid):
# Free up used id's.
self.u_id.remove(uid)
def add_item(self, name, item_id, amount, price):
user = SubElement(self.root, "item")
user.set("name", name)
user.set("itemId", str(item_id))
user.set("price", str(price))
user.set("add_time", str(time.time()))
user.set("relisted", str(0))
user.set("amount", str(amount))
user.set("uid", str(self.getId()))
self.save()
def get_uid(self, uid):
for elem in self.root:
if elem.get("uid") == str(uid):
return elem
return -10
def remove_item_uid(self, uid):
for elem in self.root:
if elem.get("uid") == str(uid):
self.root.remove(elem)
self.remove_id(uid)
self.save()
return 1
return -10
def save(self):
# Be sure to call save() after any changes to the tree.
f = open("data/sale.xml", "w")
dom = xml.dom.minidom.parseString(clean_xml(tostring(self.root)))
f.write(dom.toprettyxml(" "))
f.close()
示例11: get_id_set
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def get_id_set(url):
xml = ElementTree(file = urlopen(url))
root = xml.getroot()
ids = root.findall(".//{http://www.w3.org/2005/Atom}id")
ids.pop(0)
list = []
for i in ids:
#print i.get("{http://itunes.apple.com/rss}id")
list.append(i.get("{http://itunes.apple.com/rss}id"))
return set(list)
示例12: loadConfigFile
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def loadConfigFile(fileName): #TODO: error handling etc.
"""Loads a config file. If its an xml file, inheritances are automatically resolved."""
try:
if '.params' in fileName:
return fileToDict(fileName)
if '.xml' in fileName:
config = ElementTree()
config.parse(fileName)
resolveDocumentInheritances(config.getroot())
return config
except Exception as inst:
main_log.info('Error loading config file ' + fileName)#, inst) TODO: log exception too
main_log.info(str(inst))
return None
示例13: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def __init__(self, tipo):
from xml.etree import ElementTree as et
self.tipo = tipo
et = et.parse('../con.xml')
root = et.getroot()
for child in root.iter(tipo):
self.con_Data = {}
for cada in child:
d = cada.tag
self.d = cada.text
if cada.text == 'True' or cada.text == 'False':
self.con_Data[cada.tag] = bool(cada.text)
else:
self.con_Data[cada.tag] = cada.text
self.connect()
示例14: fillin_mainB
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def fillin_mainB(db_b, nodePath):
nonlocal indent_level
nodeXMLfile=".basket"
nodeTree = ElementTree(file=(nodePath + nodeXMLfile))
xml_rawroot = nodeTree.getroot()
xml_root = xml_rawroot.getchildren()[1]
def traverseBranch(xml_parent_b, db_parent_b, fillin_Parent = False):
nonlocal indent_level
for xml_b in xml_parent_b:
if xml_b.tag == "note":
type = xml_b.get("type")
content = xml_b.find("content").text
data = ""
if type == "html":
with open(nodePath + content) as nodeContFile:
data = nodeContFile.read()
elif type == "link" or type == "cross_reference" or type == "file" or type == "image":
data = content
else:
data = content
#print("\n Error: Unrecognized type of the note! \n")
"""
elif type == "cross_reference":
elif type == "file":
elif type == "image":
#<p><img alt="" data-cke-saved-src="www.ya.ru" src="www.ya.ru"><br></p>
"""
if ( db_parent_b.text == "" and fillin_Parent ):
print(indent(indent_level + 1) + str(content))
db_parent_b.text = data
else:
print(indent(indent_level) + "subBranch: " + str(content))
db_b = Branch(tree=curtree, main=False, folded=False, parent=db_parent_b)
db_b.text = data
if xml_b.tag == "group":
# it is first level branches and has one groupe only
if ( xml_root == xml_parent_b and len(xml_parent_b.getchildren()) == 1):
traverseBranch(xml_b, db_parent_b, fillin_Parent = False)
else:
db_b = Branch(tree=curtree, main=False, folded=xml_b.get("folded"), text="", parent=db_parent_b)
print(indent(indent_level) + "subBranch: ")
indent_level += 1
traverseBranch(xml_b, db_b, fillin_Parent = True)
indent_level -= 1
traverseBranch(xml_root, db_b)
示例15: parseXml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import getroot [as 别名]
def parseXml(filename):
filename = os.path.abspath(filename);
if not os.path.exists(filename):
raise IOError("File not found!")
etree = ElementTree(file=filename)
eroot = etree.getroot() # chemical_element_list
for elem in eroot.getchildren():
# we care only about single chemical_elements
if elem.tag != "chemical_element": continue
finalElem = update(elem)
if finalElem == None: continue
print stringifyElement(finalElem, 0)
# print tem.elemDefinition()
print tem.definition()