本文整理汇总了Python中xml.etree.ElementTree.register_namespace方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.register_namespace方法的具体用法?Python ElementTree.register_namespace怎么用?Python ElementTree.register_namespace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.register_namespace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: printDistAndPace
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def printDistAndPace(self, inputFile, prefix=_defaultPrefix):
ET.register_namespace('', 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2')
ET.register_namespace('TPX', "http://www.garmin.com/xmlschemas/UserProfile/v2")
tree = ET.parse(inputFile)
root = tree.getroot()
points = []
for lap in root.iter(prefix + "Trackpoint"):
posTag = lap.find(prefix + "Position")
if posTag is None:
continue
lat = posTag.find(prefix + "LatitudeDegrees").text
lon = posTag.find(prefix + "LongitudeDegrees").text
time = lap.find(prefix + "Time").text
timeObj = datetime.strptime(time, _dateFormat)
points.append( ((lat, lon), timeObj) )
td = points[-1][1] - points[0][1]
totalMiles = self.getMiles(points)
self.printOutput(td.seconds, totalMiles)
示例2: save_element
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def save_element(elem, path):
if elem is None:
return
if not path or path is None:
return
parent = os.path.dirname(path)
if not os.path.isdir(parent):
os.makedirs(parent, mode=0o755, exist_ok=True)
os.chmod(parent, 0o0755)
try:
# Get the elements default namespace
namespace = getNamespace(elem)
# Pretty up the element
indent(elem)
# Register the discovered namespace as the default
ET.register_namespace("", namespace)
# Create a new ElementTree with this element as the root
elem_tree = ET.ElementTree(element=elem)
# Write the full tree to a file
elem_tree.write(path, xml_declaration=False, encoding="UTF-8", method="xml")
os.chmod(path, 0o0664)
return True
except:
print(" *** Error writing new element to path %s" % path)
print(" Exception Type: ", sys.exc_info()[0])
print(" Exception Value: ", sys.exc_info()[1])
return False
示例3: fix_graphml_format_better
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def fix_graphml_format_better(cls, name, gridfs):
cls._logger.info("Reformatting file to fix GDO graphml formatting using element tree")
replacements = {}
with gridfs.get_last_version(name) as f:
tree = ElementTree.parse(f)
f_id = f._id
for key_entry in tree.findall("{http://graphml.graphdrawing.org/xmlns}key"):
key_name = key_entry.attrib['attr.name']
id = key_entry.attrib['id']
key_entry.attrib['id'] = key_name
replacements[id] = key_name
# cls._logger.info("Name: %s, Key %s", key_name, key_entry)
# cls._logger.info("Dict %s", replacements)
root=tree.getroot()
for data_entry in root.iter("{http://graphml.graphdrawing.org/xmlns}data"):
found_key = data_entry.attrib['key']
data_entry.set('key', replacements[found_key])
ElementTree.register_namespace('', "http://graphml.graphdrawing.org/xmlns")
with gridfs.new_file(filename=name, content_type="text/xml") as des:
tree.write(des, encoding='utf-8', method='xml')
cls._logger.info("Deleting old version of file %s", f_id)
gridfs.delete(f_id)
示例4: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def __init__(self, chapter):
"""
:param chapter: the chapter object
:type chapter: :py:class:`Chapter`
:return:
"""
# First, parse the package file to get to the content
ET.register_namespace('', "http://www.idpf.org/2007/opf")
root = ET.parse(os.path.join(chapter.source, "package.opf")).getroot()
# First get the simple metadata
self._title = root.find(".//{http://purl.org/dc/elements/1.1/}title").text
dt = root.find(".//{http://www.idpf.org/2007/opf}meta[@property='dcterms:date']").text
# TODO: the format string should be imported from the rp2epub package!
self._date = datetime.strptime(dt, "%Y-%m-%dT%M:%S:00Z")
self._authors = []
self._editors = []
for creator in root.findall(".//{http://purl.org/dc/elements/1.1/}creator"):
if creator.get("role", default="editor") == "author":
self._authors.append(creator.text)
else:
self._editors.append(creator.text)
# Get the manifest entries
self._manifest = self._get_manifest(chapter.target, root)
# Get the spine
self._spine = self._get_spine(chapter.target, root)
示例5: remove_office_metadata
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def remove_office_metadata(file_name):
"""
Remove all metadata from Microsoft Office 2007+ file types such as docx,
pptx, and xlsx.
:param str file_name: The path to the file whose metadata is to be removed.
"""
ns = {
'cp': 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
'dc': 'http://purl.org/dc/elements/1.1/',
'dcterms': 'http://purl.org/dc/terms/',
'dcmitype': 'http://purl.org/dc/dcmitype/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
}
for prefix, uri in ns.items():
ElementTree.register_namespace(prefix, uri)
_, file_ext = os.path.splitext(file_name)
tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name), suffix=file_ext)
os.close(tmpfd)
with zipfile.ZipFile(file_name, 'r') as zin:
with zipfile.ZipFile(tmpname, 'w') as zout:
zout.comment = zin.comment
for item in zin.infolist():
data = zin.read(item.filename)
if item.filename == 'docProps/core.xml':
root = ElementTree.fromstring(data)
root.clear()
data = ElementTree.tostring(root, 'UTF-8')
zout.writestr(item, data)
os.remove(file_name)
os.rename(tmpname, file_name)
示例6: build_DAR
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def build_DAR(urls):
""" urls consist of a list of tuples (dl_dir, url),
where dl_dir is the download directory for each url"""
if use_register:
try:
ET.register_namespace("ngeo", NGEO_URI)
ET.register_namespace("xsi", XSI_URI)
except Exception:
pass
root = ET.Element(NGEO_NS+DA_RESP,
{XSI_NS+"schemaLocation":SCHEMA_LOCATION})
ET.SubElement(root, NGEO_NS+MONITORINGSTATUS).text = "IN_PROGRESS"
pa_list = ET.SubElement(root, NGEO_NS+PRODACCESSLIST)
for url in urls:
pa = ET.SubElement(pa_list, NGEO_NS+PRODACCESS)
ET.SubElement(pa, NGEO_NS+PRODACCESSURL).text = url[1]
ET.SubElement(pa, NGEO_NS+PRODACCESSSTATUS).text = "READY"
ET.SubElement(pa, NGEO_NS+PRODDOWNLOADDIRECTORY).text = url[0]
if LOCAL_DEBUG > 0:
print "dAR:\n"+ DAR_PREAMBLE + ET.tostring(root)
return DAR_PREAMBLE + ET.tostring(root)
示例7: appendSplashActivity
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def appendSplashActivity(decompileDir, splashType):
manifestFile = decompileDir + "/AndroidManifest.xml"
manifestFile = file_utils.getFullPath(manifestFile)
ET.register_namespace('android', androidNS)
key = '{' + androidNS + '}name'
screenkey = '{' + androidNS + '}screenOrientation'
theme = '{' + androidNS + '}theme'
tree = ET.parse(manifestFile)
root = tree.getroot()
applicationNode = root.find('application')
if applicationNode is None:
return
splashNode = SubElement(applicationNode, 'activity')
splashNode.set(key, 'com.u8.sdk.SplashActivity')
splashNode.set(theme, '@android:style/Theme.Black.NoTitleBar.Fullscreen')
if splashType[:1] == '1':
splashNode.set(screenkey, 'landscape')
else:
splashNode.set(screenkey, 'portrait')
intentNode = SubElement(splashNode, 'intent-filter')
actionNode = SubElement(intentNode, 'action')
actionNode.set(key, 'android.intent.action.MAIN')
categoryNode = SubElement(intentNode, 'category')
categoryNode.set(key, 'android.intent.category.LAUNCHER')
tree.write(manifestFile, 'UTF-8')
示例8: setUp
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def setUp(self):
self.expect = ["BEGIN:VCARD", "VERSION:3.0",
"PRODID:-//Gramps//NONSGML Gramps %s//EN" % VERSION,
"FN:Lastname", "N:Lastname;;;;",
"SORT-STRING:" + "Lastname".ljust(55), "END:VCARD"]
date = time.localtime(time.time())
self.input_list = ["BEGIN:VCARD", "VERSION:3.0", "FN:Lastname",
"N:Lastname;;;;", "END:VCARD"]
self.header = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE database PUBLIC "-//GRAMPS//DTD GRAMPS XML %s//EN"
"http://gramps-project.org/xml/%s/grampsxml.dtd">""" % \
(GRAMPS_XML_VERSION, GRAMPS_XML_VERSION)
strng = """<database xmlns="http://gramps-project.org/xml/%s/">
<header>
<created date="%04d-%02d-%02d" version="%s"/>
<researcher/>
</header>
<people>
<person id="I0000" handle="_0000">
<name type="Birth Name">
<surname>Lastname</surname>
</name>
</person>
</people>
</database>""" % \
(GRAMPS_XML_VERSION, date[0], date[1], date[2], VERSION)
namespace = "http://gramps-project.org/xml/%s/" % GRAMPS_XML_VERSION
ET.register_namespace("", namespace)
self.database = ET.XML(strng)
self.people = self.database[1]
self.person = self.people[0]
self.name = self.person[0]
self.lastname = self.name[0]
示例9: AddContentProtection
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def AddContentProtection(options, container, tracks):
kids = []
for track in tracks:
kid = track.kid
if kid is None:
PrintErrorAndExit('ERROR: no encryption info found in track '+str(track))
if kid not in kids:
kids.append(kid)
xml.register_namespace('mas', MARLIN_MAS_NAMESPACE)
xml.register_namespace('mspr', PLAYREADY_MSPR_NAMESPACE)
#xml.SubElement(container, 'ContentProtection', schemeIdUri='urn:mpeg:dash:mp4protection:2011', value='cenc')
if options.marlin:
cp = xml.SubElement(container, 'ContentProtection', schemeIdUri=MARLIN_SCHEME_ID_URI)
cids = xml.SubElement(cp, '{' + MARLIN_MAS_NAMESPACE + '}MarlinContentIds')
for kid in kids:
cid = xml.SubElement(cids, '{' + MARLIN_MAS_NAMESPACE + '}MarlinContentId')
cid.text = 'urn:marlin:kid:' + kid
if options.playready_header:
if options.encryption_key:
kid = options.kid_hex
key = options.key_hex
else:
kid = kids[0]
key = None
header_b64 = ComputePlayReadyHeader(options.playready_header, kid, key)
cp = xml.SubElement(container, 'ContentProtection', schemeIdUri=PLAYREADY_SCHEME_ID_URI)
pro = xml.SubElement(cp, '{' + PLAYREADY_MSPR_NAMESPACE + '}pro')
pro.text = header_b64
示例10: SaveLayout
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def SaveLayout(self,Form = None,Fields = None,Name = None):
#find citation element
for element in self.root:
if Form in element.tag:
form = element
break
for element in form:
if 'layout' in element.tag:
form = element
break
for element in form:
form.remove(element)
bns = (self.root.tag).find('{')
ens = (self.root.tag).find('}')
ns = self.root.tag[bns+1:ens]
ET.register_namespace('',ns)
for field in Fields:
value = field
if 'text' in value:
field = ET.SubElement(form,value)
else:
field = ET.SubElement(form,'text ' + value)
self.tree.write(Name)
示例11: to_string
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def to_string(self, endpoints):
# type: (List[EndpointDescription]) -> str
"""
Converts the given endpoint description beans into a string
:param endpoints: A list of EndpointDescription beans
:return: A string containing an XML document
"""
# Make the ElementTree
root = self._make_xml(endpoints)
tree = ElementTree.ElementTree(root)
# Force the default name space
ElementTree.register_namespace("", EDEF_NAMESPACE)
# Make the XML
# Prepare a StringIO output
output = StringIO()
# Try to write with a correct encoding
tree.write(
output,
encoding=self._encoding,
xml_declaration=self._xml_declaration,
)
return output.getvalue().strip()
示例12: craete_xbrl_url_json
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def craete_xbrl_url_json(since,p):
#有報キャッチャーWebServiceのAtomAPIアドレス<http://resource.ufocatch.com/>
base_url = 'http://resource.ufocatch.com/atom/'
namespace = '{http://www.w3.org/2005/Atom}'
#有報キャッチャーのページ
page = 1 + p
count = 0
while True:
#文字列変換
t_symbol = str(page)
print('page:'+t_symbol + ', loading...')
#企業毎の有報へのデータへのリンク情報を取得
response_string = get_link_info_str(t_symbol, base_url)
#xmlをparseするElementTreeを取得
ET_tree = ET.fromstring( response_string )
ET.register_namespace('',namespace[1:-1])
#downloadファイルの対象を取得
info_dict = get_link(ET_tree,namespace,since)
count += len(info_dict)
if len(info_dict) == 0 :
#取得データがなくなり次第、処理終了
print('process' + str(p) + ':complete a download!! [' + str(count) + ']')
break
#Request用のJson形式のファイルを作成
json_directory=os.getcwd()+'/downloaded_info'
make_directory(json_directory)
ofname = json_directory+'/dat_download_'+t_symbol+'.json'
write_download_info(ofname,info_dict)
page += proc
示例13: __init__
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def __init__(self, pom):
"""
Load the specified pom.xml.
:param pom: pom to load
"""
Xml.register_namespace('', 'http://maven.apache.org/POM/4.0.0')
self.pom = Xml.parse(pom)
示例14: migrate
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def migrate(*args, **kwargs):
"""
Adds a "checksums" DictField and populates it with the known checksum type and value.
Templatizes the XML in "repodata".
:param args: unused
:type args: list
:param kwargs: unused
:type kwargs: dict
"""
try:
ET.register_namespace('rpm', RPM_NAMESPACE)
except AttributeError:
# python 2.6 doesn't have the register_namespace function
ET._namespace_map[RPM_NAMESPACE] = 'rpm'
db = connection.get_database()
rpm_collection = db['units_rpm']
srpm_collection = db['units_srpm']
drpm_collection = db['units_drpm']
for rpm in rpm_collection.find({}, ['checksum', 'checksumtype', 'repodata']):
migrate_rpm_base(rpm_collection, rpm)
for srpm in srpm_collection.find({}, ['checksum', 'checksumtype', 'repodata']):
migrate_rpm_base(srpm_collection, srpm)
migrate_drpms(drpm_collection)
示例15: processDir
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import register_namespace [as 别名]
def processDir(sourceDir, targetDir, language="en"):
ET.register_namespace('', 'http://www.loc.gov/standards/alto/ns-v2#')
for subdir, dirs, files in os.walk(sourceDir):
for file in files:
fname = os.path.join(subdir, file)
outputfname = os.path.join(
targetDir, os.path.relpath(fname, sourceDir))
if not os.path.exists(os.path.dirname(outputfname)):
os.makedirs(os.path.dirname(outputfname))
print fname
print outputfname
tree = ET.parse(fname)
entities = dict()
for t in tree.getroot().iter(tag="{http://www.loc.gov/standards/alto/ns-v2#}NamedEntityTag"):
if entities.get(t.attrib.get('LABEL')) is None:
entities[t.attrib.get('LABEL')] = []
entities.get(t.attrib.get('LABEL')).append(t)
result = disambiguation.disambiguateList(entities.keys())
for key in result.keys():
if result.get(key) is not None and result.get(key)[0] is not None:
for tag in entities[key]:
tag.set("URI", result[key][0][1:-1])
tree.write(
outputfname, xml_declaration=True, encoding='utf-8', method='xml')