本文整理汇总了Python中xml.etree.ElementTree.parse方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.parse方法的具体用法?Python ElementTree.parse怎么用?Python ElementTree.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_fuel_tanks_content
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def test_fuel_tanks_content(self):
script_path = self.sandbox.path_to_jsbsim_file('scripts', 'J2460.xml')
fdm = CreateFDM(self.sandbox)
fdm.load_script(script_path)
fdm.run_ic()
tree = et.parse(script_path)
use_tag = tree.getroot().find('use')
aircraft_name = use_tag.attrib['aircraft']
aircraft_path = self.sandbox.path_to_jsbsim_file('aircraft',
aircraft_name)
aircraft_tree = et.parse(os.path.join(aircraft_path,
aircraft_name+'.xml'))
total_fuel_quantity = 0.0
total_oxidizer_quantity = 0.0
for tank in aircraft_tree.findall('propulsion/tank'):
contents = float(tank.find('contents').text)
if tank.attrib['type'] == "FUEL":
total_fuel_quantity += contents
elif tank.attrib['type'] == 'OXIDIZER':
total_oxidizer_quantity += contents
self.assertAlmostEqual(fdm['propulsion/total-fuel-lbs'],
total_fuel_quantity)
self.assertAlmostEqual(fdm['propulsion/total-oxidizer-lbs'],
total_oxidizer_quantity)
示例2: intiMulticopy
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def intiMulticopy(self):
fio = fIO()
fio.filePrompt("folder", "Please select folder locations to copy to.\n"
+ "These folder locations will be saved.\n"
+ "When you are done loading in locations, simply\n"
+ "press the cancel button in the file explorer.\n")
try:
tree = ET.parse('filecopylocations.xml')
xroot = tree.getroot()
for locs in xroot.findall('Location'):
xroot.remove(locs)
except:
froot = ET.Element('Directories')
tree = ET.ElementTree(froot)
tree.write('filecopylocations.xml')
tree = ET.parse('filecopylocations.xml')
xroot = tree.getroot()
locnum = 1
fio.folderLocation()
floc = fio.getFolderLocation()
while(floc != ''):
try:
loc = ET.SubElement(xroot, 'Location'.format(locnum))
loc.set('index', '{0}'.format(locnum))
locnum = locnum + 1
loc.text = floc
floc = fio.getFolderLocation()
except:
floc = ''
tree.write('filecopylocations.xml')
ET.dump(xroot)
示例3: setUp
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def setUp(self):
JSBSimTestCase.setUp(self)
self.fdm = CreateFDM(self.sandbox)
self.script_path = self.sandbox.path_to_jsbsim_file('scripts',
'c1722.xml')
# Read the time step 'dt' from the script file
self.tree = et.parse(self.script_path)
root = self.tree.getroot()
use_tag = root.find('use')
aircraft_name = use_tag.attrib['aircraft']
self.run_tag = root.find('run')
self.dt = float(self.run_tag.attrib['dt'])
# Read the date at which the trim will be run
for event in root.findall('run/event'):
if event.attrib['name'] == 'Trim':
cond_tag = event.find('condition')
self.trim_date = float(cond_tag.text.split()[-1])
break
# Read the output rate and the output file from the aircraft file
aircraft_path = self.sandbox.path_to_jsbsim_file('aircraft', aircraft_name,
append_xml(aircraft_name))
tree = et.parse(aircraft_path)
output_tag = tree.getroot().find('output')
self.output_file = output_tag.attrib['name']
self.rateHz = float(output_tag.attrib['rate'])
self.rate = int(1.0 / (self.rateHz * self.dt))
示例4: getXML
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def getXML(filepath):
fext = os.path.splitext(filepath)[1]
if fext == '.gz':
tmp = GzipFile(filename=filepath)
return ET.parse(tmp)
else:
return ET.parse(filepath)
示例5: get_channels
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def get_channels(name,url):
from xml.etree import ElementTree
if url.startswith('http://'):
source = get_page_source(url)
else:
source = readfile(url)
save(os.path.join(pastaperfil,"working.xml"),source)
chlist_tree = ElementTree.parse(os.path.join(pastaperfil,"working.xml"))
LANGUAGE = "en"
groups = ElementTree.parse(os.path.join(pastaperfil,"working.xml")).findall('.//group')
for group in groups:
if group.attrib[LANGUAGE].encode('utf-8') == name:
channels = group.findall('.//channel')
for channel in channels:
try:
title = channel.find('.//name').attrib['en'].encode('utf-8')
if not title: title = channel.find('.//name').attrib['cn'].encode('utf-8')
tipo = channel.find('.//stream_type').text
sop_address = channel.find('.//item').text
if not tipo: tipo = "N/A"
if not title: title = "N/A"
thumbnail = ""
try:
thumbnail = channel.find('.//thumbnail').text
except: pass
if sop_address:
if thumbnail == "": thumbnail = addonpath + art + 'sopcast_link.png'
try: addDir_livestreams_common('[B][COLOR orange]' + title + ' [/B][/COLOR](' + tipo +')',sop_address,2,thumbnail,False)
except:pass
else: pass
except: pass
else: pass
示例6: readFile
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def readFile(filename):
"""
Open svg file and return root xml object
"""
GZIPMAGIC = '\037\213'
try:
fh = open(filename, 'rb')
except IOError:
raise SVGError("could not open file '%s' for reading" % filename)
# test for gzip compression
magic = fh.read(2)
fh.close()
if magic == GZIPMAGIC:
svg = etree.parse(GzipFile(filename, 'r'))
else:
svg = etree.parse(filename)
root = svg.getroot()
if not root.tag == Renderer.SVG_ROOT:
raise SVGError("Expected SVG fragment as root object")
return root
示例7: test_CAS_ic
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def test_CAS_ic(self):
script_name = 'Short_S23_3.xml'
script_path = self.sandbox.path_to_jsbsim_file('scripts', script_name)
# Add a Pitot angle to the Short S23
tree, aircraft_name, path_to_jsbsim_aircrafts = CopyAircraftDef(script_path, self.sandbox)
self.addPitotTube(tree.getroot(), 5.0)
tree.write(self.sandbox('aircraft', aircraft_name,
aircraft_name+'.xml'))
# Read the CAS specified in the IC file
tree = et.parse(script_path)
use_element = tree.getroot().find('use')
IC_file = use_element.attrib['initialize']
tree = et.parse(os.path.join(path_to_jsbsim_aircrafts,
append_xml(IC_file)))
vc_tag = tree.getroot().find('./vc')
VCAS = float(vc_tag.text)
if 'unit' in vc_tag.attrib and vc_tag.attrib['unit'] == 'FT/SEC':
VCAS /= 1.68781 # Converts in kts
# Run the IC and check that the model is initialized correctly
fdm = CreateFDM(self.sandbox)
fdm.set_aircraft_path('aircraft')
fdm.load_script(script_path)
fdm.run_ic()
self.assertAlmostEqual(fdm['ic/vc-kts'], VCAS, delta=1E-7)
self.assertAlmostEqual(fdm['velocities/vc-kts'], VCAS, delta=1E-7)
示例8: testExecuteStream
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def testExecuteStream(self):
q = sesame.SesameQuery()
q.names = ["ngc4258", "goob's star", "m51"]
strm = q.execute_stream()
doc = ET.parse(strm)
strm.close()
self.assertEquals("Sesame", doc.getroot().tag)
strm = q.execute_stream(astext=True)
doc = ET.parse(strm)
strm.close()
self.assertEquals("Sesame", doc.getroot().tag)
strm = q.execute_stream(format="pc")
lines = []
for line in strm:
lines.append(line)
strm.close()
self.assertTrue(lines[0].startswith(b'#'),
b"unexpected first line: " + lines[0])
self.assertTrue(lines[5].startswith(b'%'),
b"unexpected mid-line: " + lines[5])
q.dbs = "GB"
self.assertRaises(sesame.DALQueryError, q.execute_stream)
strm = q.execute_stream(lax=True)
strm.close()
del q.dbs
self.assertEquals("", q.dbs)
q.opts = "bo"
self.assertRaises(sesame.DALQueryError, q.execute_stream)
strm = q.execute_stream(lax=True)
strm.close()
示例9: merge_androidmanifest_xml
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def merge_androidmanifest_xml():
try:
from xml.etree import ElementTree as ET
ET.register_namespace('android', xmlns_android);
#extra项目
print extra_file_path+"/AndroidManifest.xml"
extra_parse = ET.parse(extra_file_path+"/AndroidManifest.xml")
extra_root = extra_parse.getroot()
#target项目
target_parse = ET.parse(target_file_path+"/AndroidManifest.xml")
target_root = target_parse.getroot()
target_application = target_root.find("application")
#合并两个项目的meta-data
merge_hkc_meta(extra_root,target_root,target_application)
#合并两个项目的activity
merge_hkc_activity(extra_root,target_root,target_application)
#合并两个项目的service
merge_hkc_services(extra_root,target_root,target_application)
target_parse.write(target_file_path+"/AndroidManifest.xml","utf-8",True)
except Exception, e:
print "merge_androidmanifest_xml "+str(e)
示例10: redefine_app_name
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def redefine_app_name():
print "\n 新名字: hkc_app_name"
try:
from xml.etree import ElementTree as ET
ET.register_namespace('android', xmlns_android);
target_parse = ET.parse(target_file_path+"/AndroidManifest.xml")
target_root = target_parse.getroot()
target_application = target_root.find("application")
orig_name = target_application.attrib[xmlns_android_attrib+"label"]
print "orig_name:\t"+orig_name
target_application.attrib[xmlns_android_attrib+"label"] = "@string/hkc_app_name"
target_parse.write(target_file_path+"/AndroidManifest.xml","utf-8",True)
target_strings_parse = ET.parse(target_file_path+"/res/values/strings.xml")
target_string_root = target_strings_parse.getroot()
strings_item = target_string_root.findall("string")
for string_i in strings_item:
if orig_name.find(string_i.attrib['name'])==8 :
print string_i.text
string_i.text = "@string/hkc_app_name"
target_strings_parse.write(target_file_path+"/res/values/strings.xml","utf-8",True)
except Exception, e:
print "redefine_app_name "+str(e)
示例11: main
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def main(toc_path, output_path):
tree = ET.parse(join(toc_path, "TOC.xml"))
root = tree.getroot()
#output file
if not exists(output_path):
makedirs(output_path)
filePath = join(output_path, root.attrib['RELEASE_NO'])
with open(filePath, 'w+') as output_file:
publication = root.attrib["PUBLICATION"]
print root.attrib
Meta = root.findall("./Head_np/Meta")
publication_date= Meta[0].attrib["BASE_HREF"]
sections = root.findall("./Body_np/Section")
u = [("publication_date","entity_id")]
for section in sections:
pages = section.findall('Page')
for page in pages:
href = page.attrib['HREF']
page_path = join(toc_path, href[1:] + '.xml')
page_xml = ET.parse(page_path)
entities = page_xml.findall('Entity')
for entity in entities:
entity_ID = entity.attrib['ID']
entity_path = join(publication_date, entity_ID)
entity_tuple=(publication_date,entity_ID)
u.append(entity_tuple)
print u
示例12: setLayerStyle
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def setLayerStyle(self, layerWorkspace, dataStoreName, layerName, styleWorkspace, styleName):
""" Set the default style of given layer.
Set styleWorkspace to None to refer to styles with no workspace.
"""
# Open the style XML
stylePath = self.getStyleXmlPath(styleWorkspace, styleName)
styleTree = Xml.parse(stylePath)
styleRoot = styleTree.getroot()
logging.debug("[GsXml][setLayerStyle] Assigning style '%s'"% stylePath)
# Get the style id
styleId = styleRoot.find("./id").text #<style><id>
logging.debug("[GsXml][setLayerStyle] with <Id> '%s'"% styleId)
# Open the layer XML
layerPath = self.getLayerPath(layerWorkspace, dataStoreName, layerName)
layerTree = Xml.parse(layerPath)
layerRoot = layerTree.getroot()
logging.debug("[GsXml][setLayerStyle] to layer '%s'"% layerPath)
# Change the default style
layerRoot.find("./defaultStyle/id").text = styleId #<layer><defaultStyle<id>
# Write the layer file
layerTree.write(layerPath)
logging.debug("[GsXml][setLayerStyle] Style assigned")
示例13: ModRowWith
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def ModRowWith(self, withAttrs, withValues, inThisTable, thatAttrs, thatValues):
dataToModify = self.GetRowWith(withAttrs, withValues, inThisTable)
nameToLocation = {}
index = 0
self.DelRowWith(withAttrs, withValues, inThisTable)
structure = XML.parse(self.brain.GetTableFileName(inThisTable, self.use)).getroot()
for field in XML.parse(self.brain.GetTableFileName(inThisTable, self.use)).getroot()[1]:
nameToLocation[field.attrib["Name"]] = index
index += 1
for i in range(len(thatAttrs)):
for k in range(len(dataToModify)):
dataToModify[k][nameToLocation[thatAttrs[i]]] = thatValues[i]
for data in dataToModify:
entryTag = XML.Element("Entry")
for datum in data:
dTag = XML.Element("D")
dTag.text = datum
entryTag.append(dTag)
structure[2].append(entryTag)
with open(self.brain.GetTableFileName(inThisTable, self.use), "w") as outputFile:
XML.ElementTree(structure).write(outputFile)
示例14: test_subreadset_metadata_element_name
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def test_subreadset_metadata_element_name(self):
# without touching the element:
sset = SubreadSet(data.getXml(10))
log.debug(data.getXml(10))
fn = tempfile.NamedTemporaryFile(suffix=".subreadset.xml").name
log.debug(fn)
sset.write(fn)
f = ET.parse(fn)
self.assertEqual(len(f.getroot().findall(
'{http://pacificbiosciences.com/PacBioDatasets.xsd}'
'SubreadSetMetadata')),
0)
self.assertEqual(len(f.getroot().findall(
'{http://pacificbiosciences.com/PacBioDatasets.xsd}'
'DataSetMetadata')),
1)
# with touching the element:
sset = SubreadSet(data.getXml(10))
sset.metadata.description = 'foo'
fn = tempfile.NamedTemporaryFile(suffix=".subreadset.xml").name
sset.write(fn, validate=False)
f = ET.parse(fn)
self.assertEqual(len(f.getroot().findall(
'{http://pacificbiosciences.com/PacBioDatasets.xsd}'
'SubreadSetMetadata')),
0)
self.assertEqual(len(f.getroot().findall(
'{http://pacificbiosciences.com/PacBioDatasets.xsd}'
'DataSetMetadata')),
1)
示例15: getServers
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import parse [as 别名]
def getServers(self):
xmlSvrRoot = ET.parse(self.serverXML).getroot()
xmlUplRoot = ET.parse(self.uplinkXML).getroot()
servers = []
for svr in xmlSvrRoot.iter(XMLServerDAO.SERVER):
# Let's dynamically load the class definition
svrClassName = svr.find(Server.SERVER_CLASS).text
svrClass = self.getServerClass(svrClassName)
# Retrieve the server information
args = []
for attr in Server.SERVER_ARGS:
args.append(svr.find(attr).text)
# Retrieve the uplink information
uplink = svr.find(Server.SERVER_UPLINK).text
for upl in xmlUplRoot.iter(Server.SERVER_UPLINK):
if (upl.find(Server.SERVER_UPLINK_NAME).text == uplink):
for attr in Server.UPLINK_ARGS:
args.append(upl.find(attr).text)
break
# Retrieve extra information related to the server class type
for attr in svrClass.SERVER_ARGS:
args.append(svr.find(attr).text)
# Add the server to the list of servers
servers.append(svrClass(*args))
return servers