本文整理汇总了Python中lxml.etree.ElementTree.getroot方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.getroot方法的具体用法?Python ElementTree.getroot怎么用?Python ElementTree.getroot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lxml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.getroot方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_from_element
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def test_from_element(self):
elem = Element('document')
tree = ElementTree(elem)
self.assertEqual('document', tree.getroot().tag)
with open('sample.xml') as f:
et = ElementTree(file=f)
root = et.getroot()
tree = ElementTree(root)
self.assertEqual(root.base, tree.getroot().base)
self.assertEqual(et.docinfo.URL, tree.docinfo.URL)
示例2: test_etree_from_file
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def test_etree_from_file(self):
with open('sample.xml') as f:
et = ElementTree(file=f)
root = et.getroot()
self.assertEqual('{http://example.tld}document', root.tag)
self.assertEqual('x', root.prefix)
self.assertTrue('x' in root.nsmap)
with open('hello.xml') as f:
et = ElementTree(file=f)
root = et.getroot()
self.assertEqual('hello', root.tag)
self.assertEqual(None, root.prefix)
self.assertEqual({}, root.nsmap)
示例3: loadProject_0_1
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def loadProject_0_1(projectFile):
# Parse the XML Document as 0.1 version
tree = ElementTree()
tree.parse(projectFile)
xmlProject = tree.getroot()
# Register the namespace
etree.register_namespace("netzob", PROJECT_NAMESPACE)
etree.register_namespace("netzob-common", COMMON_NAMESPACE)
projectID = str(xmlProject.get("id"))
projectName = xmlProject.get("name", "none")
projectCreationDate = TypeConvertor.xsdDatetime2PythonDatetime(xmlProject.get("creation_date"))
projectPath = xmlProject.get("path")
project = Project(projectID, projectName, projectCreationDate, projectPath)
description = xmlProject.get("description")
project.setDescription(description)
# Parse the configuration
if xmlProject.find("{" + PROJECT_NAMESPACE + "}configuration") is not None:
projectConfiguration = ProjectConfiguration.loadProjectConfiguration(
xmlProject.find("{" + PROJECT_NAMESPACE + "}configuration"), PROJECT_NAMESPACE, "0.1"
)
project.setConfiguration(projectConfiguration)
# Parse the vocabulary
if xmlProject.find("{" + PROJECT_NAMESPACE + "}vocabulary") is not None:
projectVocabulary = Vocabulary.loadVocabulary(
xmlProject.find("{" + PROJECT_NAMESPACE + "}vocabulary"),
PROJECT_NAMESPACE,
COMMON_NAMESPACE,
"0.1",
project,
)
project.setVocabulary(projectVocabulary)
# Parse the grammar
if xmlProject.find("{" + PROJECT_NAMESPACE + "}grammar") is not None:
projectGrammar = Grammar.loadGrammar(
xmlProject.find("{" + PROJECT_NAMESPACE + "}grammar"), projectVocabulary, PROJECT_NAMESPACE, "0.1"
)
if projectGrammar is not None:
project.setGrammar(projectGrammar)
# Parse the simulator
if xmlProject.find("{" + PROJECT_NAMESPACE + "}simulator") is not None:
projectSimulator = Simulator.loadSimulator(
xmlProject.find("{" + PROJECT_NAMESPACE + "}simulator"),
PROJECT_NAMESPACE,
"0.1",
project.getGrammar().getAutomata(),
project.getVocabulary(),
)
if projectSimulator is not None:
project.setSimulator(projectSimulator)
return project
示例4: retrieveMessagesFromFiles
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def retrieveMessagesFromFiles(self):
# We read each file and create one message for each file
self.messages = []
self.lineView.get_model().clear()
for file in self.filesToBeImported:
from netzob.Common.ResourcesConfiguration import ResourcesConfiguration
xmlSchemaPath = os.path.join(ResourcesConfiguration.getStaticResources(), "xsds/0.1/common.xsd")
# If we find a version which validates the XML, we parse with the associated function
if not Workspace.isSchemaValidateXML(xmlSchemaPath, file):
logging.error(_("The specified XML file {0} is not valid according to the XSD ({1}).").format(str(file), str(xmlSchemaPath)))
else:
logging.debug(_("XML file valid according to the XSD schema"))
# Parse the XML Document as 0.1 version
tree = ElementTree()
tree.parse(file)
xmlFile = tree.getroot()
for xmlMessage in xmlFile.findall("{" + Project.COMMON_NAMESPACE + "}message"):
message = AbstractMessageFactory.loadFromXML(xmlMessage, Project.COMMON_NAMESPACE, "0.1")
logging.debug(_("XML String data: {0}").format(message.getStringData()))
self.messages.append(message)
self.lineView.get_model().append(None, [str(message.getID()), message.getType(), message.getStringData()])
示例5: create_IdpRequest
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def create_IdpRequest(self,key, issuer):
time=strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
id = uuid.uuid4()
doc = ElementTree(fromstring(self.tmpl_req))
doc.getroot().set("ID", id.urn)
doc.getroot().set("IssueInstant", time)
for node in doc.getroot().iter():
if node.tag == "{urn:oasis:names:tc:SAML:2.0:assertion}Issuer":
node.text = issuer
# node = xmlsec.findNode(doc, "Issuer")
# node.text = issuer
#print self.sign(doc,key)
#print self.encodeReq(self.sign(doc,key))
return self.encodeReq(self.sign(doc,key))
示例6: get_info
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def get_info(path):
e = ET(file = path)
items = []
# hack, it might not always be [1]. it just is on here
for f in e.getroot()[1]:
items.insert(0, (f.get('name'), 'file://' + os.path.join(os.path.dirname(path), f.get('link'))))
return items
示例7: loadProject_0_1
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def loadProject_0_1(projectFile):
# Parse the XML Document as 0.1 version
tree = ElementTree()
tree.parse(projectFile)
xmlProject = tree.getroot()
# Register the namespace
etree.register_namespace('netzob', PROJECT_NAMESPACE)
etree.register_namespace('netzob-common', COMMON_NAMESPACE)
projectID = xmlProject.get('id')
projectName = xmlProject.get('name', 'none')
projectCreationDate = TypeConvertor.xsdDatetime2PythonDatetime(xmlProject.get('creation_date'))
projectPath = xmlProject.get('path')
project = Project(projectID, projectName, projectCreationDate, projectPath)
# Parse the configuration
if xmlProject.find("{" + PROJECT_NAMESPACE + "}configuration") != None:
projectConfiguration = ProjectConfiguration.loadProjectConfiguration(xmlProject.find("{" + PROJECT_NAMESPACE + "}configuration"), PROJECT_NAMESPACE, "0.1")
project.setConfiguration(projectConfiguration)
# Parse the vocabulary
if xmlProject.find("{" + PROJECT_NAMESPACE + "}vocabulary") != None:
projectVocabulary = Vocabulary.loadVocabulary(xmlProject.find("{" + PROJECT_NAMESPACE + "}vocabulary"), PROJECT_NAMESPACE, COMMON_NAMESPACE, "0.1", project)
project.setVocabulary(projectVocabulary)
# Parse the grammar
if xmlProject.find("{" + PROJECT_NAMESPACE + "}grammar") != None:
projectGrammar = Grammar.loadGrammar(xmlProject.find("{" + PROJECT_NAMESPACE + "}grammar"), projectVocabulary, PROJECT_NAMESPACE, "0.1")
if projectGrammar != None:
project.setGrammar(projectGrammar)
return project
示例8: getNameOfProject
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def getNameOfProject(workspace, projectDirectory):
projectFile = os.path.join(os.path.join(workspace.getPath(), projectDirectory), Project.CONFIGURATION_FILENAME)
# verify we can open and read the file
if projectFile == None:
return None
# is the projectFile is a file
if not os.path.isfile(projectFile):
logging.warn("The specified project's configuration file (" + str(projectFile) + ") is not valid : its not a file.")
return None
# is it readable
if not os.access(projectFile, os.R_OK):
logging.warn("The specified project's configuration file (" + str(projectFile) + ") is not readable.")
return None
# We validate the file given the schemas
for xmlSchemaFile in Project.PROJECT_SCHEMAS.keys():
xmlSchemaPath = os.path.join(ResourcesConfiguration.getStaticResources(), xmlSchemaFile)
# If we find a version which validates the XML, we parse with the associated function
if Project.isSchemaValidateXML(xmlSchemaPath, projectFile):
logging.debug("The file " + str(projectFile) + " validates the project configuration file.")
tree = ElementTree()
tree.parse(projectFile)
xmlProject = tree.getroot()
# Register the namespace
etree.register_namespace('netzob', PROJECT_NAMESPACE)
etree.register_namespace('netzob-common', COMMON_NAMESPACE)
projectName = xmlProject.get('name', 'none')
if projectName != None and projectName != 'none':
return projectName
else:
logging.warn("The project declared in file (" + projectFile + ") is not valid")
return None
示例9: produce_settings_file
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def produce_settings_file(self, printer):
printer_name = printer['name']
tree = ElementTree()
tree.parse(StringIO(XML_TEMPLATE.replace('\n', '').replace('\r', '').replace('\t', '')))
name_node = tree.find('name')
name_node.text = 'AirPrint %s @ %%h' % printer_name
service_node = tree.find('service')
port_node = service_node.find('port')
port_node.text = '%d' % printer['port']
host = printer['host']
if host:
if self.dnsdomain:
pair = host.rsplit('.', 1)
if len(pair) > 1:
host = '.'.join((pair[0], self.dnsdomain))
service_node.append(self.new_node('host-name', host))
txt = printer['txt']
for key in txt:
if self.adminurl or key != 'adminurl':
service_node.append(self.new_txtrecord_node('%s=%s' % (key, txt[key])))
source = printer['SOURCE'] if printer.has_key('SOURCE') else ''
fname = '%s%s%s.service' % (self.prefix, '%s-' % source if len(source) > 0 else '', printer_name)
if self.directory:
fname = os.path.join(self.directory, fname)
f = open(fname, 'w')
if etree:
tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8")
else:
xmlstr = tostring(tree.getroot())
doc = parseString(xmlstr)
dt= minidom.getDOMImplementation('').createDocumentType('service-group', None, 'avahi-service.dtd')
doc.insertBefore(dt, doc.documentElement)
doc.writexml(f)
f.close()
if self.verbose:
src = source if len(source) > 0 else 'unknown'
sys.stderr.write('Created from %s: %s%s' % (src, fname, os.linesep))
示例10: __init__
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def __init__(self, name):
self.name = name
tree = ElementTree(file = name)
labels = tuple((elt.tag.strip(), elt.text.strip()) for elt in tree.find("labels"))
self.labels = tuple(pair[0] for pair in labels)
self.descrs = dict(labels)
self.date = tree.getroot().get("date")
for elt in tree.findall("validation_status"):
status = elt.get("status")
uri = elt.text.strip()
if status.startswith("rsync_transfer_") or elt.get("generation") != "current":
continue
if uri not in self:
self[uri] = Object(self, uri)
self[uri].add(status)
示例11: encode_exception
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def encode_exception(self, message, version, code, locator=None):
exception_attributes = {"exceptionCode": code}
if locator:
exception_attributes["locator"] = locator
exception_text = (OWS("ExceptionText", message),) if message else ()
xml_tree = ElementTree(
OWS(
"ExceptionReport",
OWS("Exception", *exception_text, **exception_attributes),
version=version,
**{ns_xml("lang"): "en"}
)
)
xls_url = getattr(settings, "OWS11_EXCEPTION_XSL", None)
if xls_url:
xml_tree.getroot().addprevious(
ProcessingInstruction("xml-stylesheet", 'type="text/xsl" href="%s"' % xls_url)
)
return xml_tree
示例12: loadWorkspace_0_1
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def loadWorkspace_0_1(workspacePath, workspaceFile):
# Parse the XML Document as 0.1 version
tree = ElementTree()
tree.parse(workspaceFile)
xmlWorkspace = tree.getroot()
wsName = xmlWorkspace.get('name', 'none')
wsCreationDate = TypeConvertor.xsdDatetime2PythonDatetime(xmlWorkspace.get('creation_date'))
# Parse the configuration to retrieve the main paths
xmlWorkspaceConfig = xmlWorkspace.find("{" + WORKSPACE_NAMESPACE + "}configuration")
pathOfTraces = xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}traces").text
pathOfLogging = None
if xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}logging") != None and xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}logging").text != None and len(xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}logging").text) > 0:
pathOfLogging = xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}logging").text
pathOfPrototypes = None
if xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}prototypes") != None and xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}prototypes").text != None and len(xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}prototypes").text) > 0:
pathOfPrototypes = xmlWorkspaceConfig.find("{" + WORKSPACE_NAMESPACE + "}prototypes").text
lastProject = None
if xmlWorkspace.find("{" + WORKSPACE_NAMESPACE + "}projects") != None:
xmlProjects = xmlWorkspace.find("{" + WORKSPACE_NAMESPACE + "}projects")
if xmlProjects.get("last", "none") != "none":
lastProject = xmlProjects.get("last", "none")
# Instantiation of the workspace
workspace = Workspace(wsName, wsCreationDate, workspacePath, pathOfTraces, pathOfLogging, pathOfPrototypes)
# Load the already imported traces
if xmlWorkspace.find("{" + WORKSPACE_NAMESPACE + "}traces") != None:
xmlTraces = xmlWorkspace.find("{" + WORKSPACE_NAMESPACE + "}traces")
for xmlTrace in xmlTraces.findall("{" + WORKSPACE_NAMESPACE + "}trace"):
trace = ImportedTrace.loadTrace(xmlTrace, WORKSPACE_NAMESPACE, COMMON_NAMESPACE, "0.1", workspace.getPathOfTraces())
if trace != None:
workspace.addImportedTrace(trace)
# Reference the projects
if xmlWorkspace.find("{" + WORKSPACE_NAMESPACE + "}projects") != None:
for xmlProject in xmlWorkspace.findall("{" + WORKSPACE_NAMESPACE + "}projects/{" + WORKSPACE_NAMESPACE + "}project"):
project_path = xmlProject.get("path")
workspace.referenceProject(project_path)
if project_path == lastProject and lastProject != None:
workspace.referenceLastProject(lastProject)
return workspace
示例13: hasPendingModifications
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def hasPendingModifications(self, workspace):
result = True
# TODO : Some errors may occur here...
try:
tree = ElementTree(self.generateXMLConfigFile())
currentXml = etree.tostring(tree)
tree.parse(os.path.join(os.path.join(os.path.join(workspace.getPath(), "projects"), self.getPath()), Project.CONFIGURATION_FILENAME))
xmlProject = tree.getroot()
oldXml = etree.tostring(xmlProject)
if currentXml == oldXml:
result = False
except:
pass
return result
示例14: _readMessagesFromFile
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def _readMessagesFromFile(self, filePath):
from netzob.Common.ResourcesConfiguration import ResourcesConfiguration
xmlSchemaPath = os.path.join(ResourcesConfiguration.getStaticResources(), "xsds/0.1/common.xsd")
# If we find a version which validates the XML, we parse with the associated function
if not Workspace.isSchemaValidateXML(xmlSchemaPath, filePath):
logging.error("The specified XML file {0} is not valid "
"according to the XSD ({1}).".format(filePath, xmlSchemaPath))
else:
logging.debug("XML file valid according to the XSD schema")
# Parse the XML Document as 0.1 version
tree = ElementTree()
tree.parse(filePath)
xmlFile = tree.getroot()
for xmlMessage in xmlFile.findall("{" + Project.COMMON_NAMESPACE + "}message"):
message = AbstractMessageFactory.loadFromXML(xmlMessage, Project.COMMON_NAMESPACE, "0.1")
logging.debug("XML String data: " + message.getStringData())
self.messages.append(message)
示例15: save
# 需要导入模块: from lxml.etree import ElementTree [as 别名]
# 或者: from lxml.etree.ElementTree import getroot [as 别名]
def save(self, root, namespace_workspace, namespace_common, pathOfTraces):
xmlTrace = etree.SubElement(root, "{" + namespace_workspace + "}trace")
xmlTrace.set("date", str(TypeConvertor.pythonDatetime2XSDDatetime(self.getDate())))
xmlTrace.set("type", str(self.getType()))
xmlTrace.set("description", str(self.getDescription()))
xmlTrace.set("name", str(self.getName()))
xmlTrace.set("id", str(self.getID()))
# Creation of the XML File (in buffer)
# Compress it using gzip and save the .gz
tracesFile = os.path.join(pathOfTraces, str(self.getID()) + ".gz")
logging.info("Save the trace " + str(self.getID()) + " in " + tracesFile)
# Register the namespace (2 way depending on the version)
try:
etree.register_namespace('netzob-common', namespace_common)
except AttributeError:
etree._namespace_map[namespace_common] = 'netzob-common'
# Save the messages
root = etree.Element("{" + namespace_workspace + "}trace")
root.set("id", str(self.getID()))
xmlMessages = etree.SubElement(root, "{" + namespace_workspace + "}messages")
for message in self.getMessages():
AbstractMessageFactory.save(message, xmlMessages, namespace_workspace, namespace_common)
# Save the sessions
xmlSessions = etree.SubElement(root, "{" + namespace_workspace + "}sessions")
for session in self.getSessions():
session.save(xmlSessions, namespace_workspace, namespace_common)
tree = ElementTree(root)
contentOfFile = str(etree.tostring(tree.getroot()))
# if outputfile already exists we delete it
if os.path.isfile(tracesFile):
logging.debug("The compressed version (" + tracesFile + ") of the file already exists, we replace it with the new one")
os.remove(tracesFile)
# Compress and write the file
gzipFile = gzip.open(tracesFile, 'wb')
gzipFile.write(contentOfFile)
gzipFile.close()