def write_structmd(source_file, temp_dir, file_list_): """ :return: """ ET.register_namespace("dla", "https://wwik-prod.dla-marbach.de/line/") root = ET.Element("{https://wwik-prod.dla-marbach.de/line/}fileMap") for archive_entry_ in file_list_: for element_ in file_list_[archive_entry_]: if os.path.isdir(element_): dir_ = ET.SubElement( root, "{https://wwik-prod.dla-marbach.de/line/}dir") dir_.set("name", element_) else: file_ = ET.SubElement( root, "{https://wwik-prod.dla-marbach.de/line/}file") u_element = unicode(element_, "utf-8", "ignore") file_.set("name", u_element) file_size = ET.SubElement( file_, "{https://wwik-prod.dla-marbach.de/line/}size") file_size.text = str(file_list_[archive_entry_][element_]) tree = ET.ElementTree(root) tree.write(str(temp_dir) + "/" + source_file + "_structmd.xml", encoding="UTF-8", pretty_print=True, xml_declaration=True)
def create_xml(csvTrades): class XMLNamespaces: core = 'http://cmegroup.com/schema/core/1.2' etree.register_namespace('core', 'http://cmegroup.com/schema/core/1.2') root = etree.Element(etree.QName(XMLNamespaces.core, 'marginReq'), nsmap={'core': XMLNamespaces.core}) margin = etree.SubElement(root, 'margin') transactions = etree.SubElement(margin, 'transactions') transaction = etree.SubElement(transactions, 'transaction', type="TRADE", id="0") payload = etree.SubElement(transaction, 'payload', encoding="STRING", format="CSV") stringval = etree.SubElement(payload, 'string') stringval.text = csvTrades return etree.tostring(root, method='xml')
def to_etree(self, source): etree.register_namespace("junos", NS_JUNOS) configuration = { XML_NS: 'http://xml.juniper.net/xnm/1.1/xnm', XML_ATTRIBUTES: { "xmlns": "http://xml.juniper.net/xnm/1.1/xnm", "{" + NS_JUNOS + "}commit-seconds": "1411928899", "{" + NS_JUNOS + "}commit-localtime": "2014-09-28 14:28:19 EDT", "{" + NS_JUNOS + "}commit-user": "******" } } _add_if_not_empty( configuration, "interfaces", self._extract_interfaces(self.configurations[source])) _add_if_not_empty(configuration, "protocols", extract_protocols(self.configurations[source])) _add_if_not_empty(configuration, "vlans", [{ "vlan": vlan_to_etree(vlan) } for vlan in self.configurations[source].vlans]) return dict_2_etree({"data": {"configuration": configuration}})
def _nsmap(self): nsmap = {} for name, ns in self.namespaces.items(): for prefix, uri in ns.items(): register_namespace(prefix, uri) nsmap.update({prefix: uri}) return nsmap
def effect(self): # Register the namespace prefix both with etree and inkscape etree.register_namespace("laser", self.LASER_NAMESPACE) inkex.utils.NSS["laser"] = self.LASER_NAMESPACE for elementID in self.options.ids: element = self.svg.getElementById(elementID) if element.tag == "{http://www.w3.org/2000/svg}rect": self.rectangleSettings(element, self.options) if self.options.rect_kerf_adjust != "none": element.set(inkex.addNS("kerf-adjust", self.LASER_PREFIX), self.options.rect_kerf_adjust) else: element.attrib.pop( inkex.addNS("kerf-adjust", self.LASER_PREFIX), None) # Remove it if nothing to do if self.options.rect_origin == "": element.attrib.pop(inkex.addNS("origin", self.LASER_PREFIX), None) # Remove it if nothing to do else: element.set(inkex.addNS("origin", self.LASER_PREFIX), self.options.rect_origin) if self.options.action == "file": element.attrib.pop(inkex.addNS("action", self.LASER_PREFIX), None) # Remove it if nothing to do else: element.set(inkex.addNS("action", self.LASER_PREFIX), self.options.action)
def _generate_saml_request(self, ticket_id): prefixes = { 'SOAP-ENV': 'http://schemas.xmlsoap.org/soap/envelope/', 'samlp': 'urn:oasis:names:tc:SAML:1.0:protocol' } def _generate_ns_element(prefix, element): return etree.QName(prefixes[prefix], element) for prefix, uri in prefixes.items(): etree.register_namespace(prefix, uri) envelope = etree.Element(_generate_ns_element('SOAP-ENV', 'Envelope')) etree.SubElement(envelope, _generate_ns_element('SOAP-ENV', 'Header')) body = etree.SubElement(envelope, _generate_ns_element('SOAP-ENV', 'Body')) request = etree.Element(_generate_ns_element('samlp', 'Request')) request.set('MajorVersion', '1') request.set('MinorVersion', '1') request.set('RequestID', uuid4().hex) request.set('IssueInstant', datetime.datetime.utcnow().strftime(DATETIME_FORMAT)) artifact = etree.SubElement( request, _generate_ns_element('samlp', 'AssertionArtifact')) artifact.text = ticket_id body.append(request) return etree.tostring(envelope, encoding='UTF-8')
def __init__(self): """ Constructor. Defines the "--name" option of a script. """ # Call the base class constructor. inkex.Effect.__init__(self) #import matplotlib #Define string option "--name" with "-n" shortcut and default value "World". self.arg_parser.add_argument('-n', '--name', action='store', type=str, dest='name', default='none', help='Name axis') inkex.NSS[u"figurefirst"] = u"http://flyranch.github.io/figurefirst/" try: etree.register_namespace("figurefirst", "http://flyranch.github.io/figurefirst/") except AttributeError: #inkex.etree._NamespaceRegistry.update(inkex.addNS("name", "figurefirst")) #This happens on windows version of inkscape - it might be good to check #and see if the namespace has been correctly added to the document pass
def createElement(self, tag, text=None, attr=None, prefix='w', attrprefix='') : if prefix : etree.register_namespace(prefix, defaults.WPREFIXES[prefix]) element = etree.Element('{' + defaults.WPREFIXES[prefix] + '}' + tag, nsmap=None) else : element = etree.Element(tag) if attr : if attrprefix == '' : attrprefix = prefix for key, value in attr.items() : #id when hyperlink (relationship) if key == 'rel_id' or key == 'embed' : if key == 'rel_id' : element.set('{' + defaults.WPREFIXES['r'] + '}id', value) else : element.set('{' + defaults.WPREFIXES['r'] + '}' + key, value) elif not attrprefix : element.set(key, value) else : element.set('{' + defaults.WPREFIXES[attrprefix] + '}' + key, value) if text : element.text = text return element
def __init__(self, module, result, oigcfile): self.module = module self.result = result self.tree = etree.parse(oigcfile) for key in ns: etree.register_namespace(key, ns[key]) self.root = self.tree.getroot()
def cts_metadata(urn): """ Retrieve metadata from URN using catalog atom feed """ urn = MyCapytain.common.reference.URN(urn) group_file = "output/canonical-{namespace}/data/{group}/__cts__.xml".format(namespace=urn[2], group=urn[3]) work_file = "output/canonical-{namespace}/data/{group}/{work}/__cts__.xml".format(namespace=urn[2], group=urn[3], work=urn[4]) # Make sure dir exists os.makedirs(os.path.dirname(work_file), exist_ok=True) url = "http://data.perseus.org/catalog/{urn}/atom".format(urn=str(urn)) atom = requests.get(url) atom.raise_for_status() with open("cache/"+urn[3]+"."+urn[4]+"."+urn[5]+".atom", "w") as atom_write: atom_write.write(atom.text) with open("cache/"+urn[3]+"."+urn[4]+"."+urn[5]+".atom") as atom: xml = MyCapytain.common.utils.xmlparser(atom) ns = { "cts" : "http://chs.harvard.edu/xmlns/cts/ti", "ti": "http://chs.harvard.edu/xmlns/cts" } etree.register_namespace('ti', 'http://chs.harvard.edu/xmlns/cts') textgroup = xml.xpath("//cts:textgroup[@urn='"+urn["textgroup"]+"']", namespaces=ns)[0] # Change namespaces textgroup.tag = "{http://chs.harvard.edu/xmlns/cts}textgroup" for node in textgroup.xpath(".//*"): node.tag = "{http://chs.harvard.edu/xmlns/cts}"+node.tag.split("}")[-1] work = textgroup.xpath("./ti:work", namespaces=ns)[0] textgroup.remove(work) work.set("groupUrn", urn["textgroup"]) ed_tr = work.xpath(".//ti:edition|.//ti:translation", namespaces=ns)[0] ed_tr.set("workUrn", urn["work"]) with open(group_file, "w") as g: g.write(etree.tostring(textgroup, encoding=str)) try: with open(work_file) as w: e = etree.parse(w) root = e.getroot() for ed in root.xpath("./ti:edition|./ti:translation", namespaces=ns): if ed.get("urn") == str(urn): ed.getparent().remove(ed) root.extend(work.xpath("./ti:edition|./ti:translation", namespaces=ns)) work = root except Exception as E: pass with open(work_file, "w") as w: w.write(etree.tostring(work, encoding=str))
def __init__(self, filename, pretty_xml=True, data_format="HDF"): from lxml import etree as ET assert data_format in ["XML", "Binary", "HDF"], ( "Unknown XDMF data format " "'{}' (use 'XML', 'Binary', or 'HDF'.)".format(data_format) ) self.filename = filename self.data_format = data_format self.data_counter = 0 self.pretty_xml = pretty_xml if data_format == "HDF": import h5py self.h5_filename = os.path.splitext(self.filename)[0] + ".h5" self.h5_file = h5py.File(self.h5_filename, "w") self.xdmf_file = ET.Element("Xdmf", Version="3.0") self.domain = ET.SubElement(self.xdmf_file, "Domain") self.collection = ET.SubElement( self.domain, "Grid", Name="TimeSeries_meshio", GridType="Collection", CollectionType="Temporal", ) ET.register_namespace("xi", "https://www.w3.org/2001/XInclude/") self.has_mesh = False self.mesh_name = None return
def __init__(self): """ Constructor. Defines the "--spinespec" option of a script. """ # Call the base class constructor. inkex.Effect.__init__(self) #import matplotlib #Define string option "--spinespec" with "-sp" shortcut and default value "left,bottom". self.arg_parser.add_argument( '-s', '--spinespec', action='store', type=str, dest='spinespec', default='left,bottom', help= "Add a spine specification as a comma separated list of spine locations. \n Valid values are: top,bottom,right or left" ) inkex.NSS[u"figurefirst"] = u"http://flyranch.github.io/figurefirst/" try: etree.register_namespace("figurefirst", "http://flyranch.github.io/figurefirst/") except AttributeError: #inkex.etree._NamespaceRegistry.update(inkex.addNS("name", "figurefirst")) #This happens on windows version of inkscape - it might be good to check #and see if the namespace has been correctly added to the document pass
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
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
def change_root_node_properties(file, kv_map, is_delete=False): '''修改/增加 /删除 节点的属性及属性值 nodelist: 节点列表 kv_map:属性及属性值map''' ET.register_namespace("dble", "http://dble.cloud/") tree = ET.parse(file) rootnode = tree.getroot() for key in kv_map: if is_delete: if key in rootnode.attrib: del rootnode.attrib[key] else: rootnode.set(key, kv_map.get(key)) doctype = "" if file.find('rule.xml') > -1: doctype = '<!DOCTYPE dble:rule SYSTEM "rule.dtd">' elif file.find('schema.xml') > -1: doctype = '<!DOCTYPE dble:schema SYSTEM "schema.dtd">' elif file.find('server.xml') > -1: doctype = '<!DOCTYPE dble:server SYSTEM "server.dtd">' xmlstr = ET.tostring(tree, encoding="utf-8", xml_declaration=True, doctype=doctype) with open(file, 'wb') as f: f.writelines(xmlstr)
def create_image_filter(header, nsmap): img_ns = nsmap['PDS4::IMG']['namespace'] etree.register_namespace("img", img_ns) optical_filter = etree.Element(etree.QName(img_ns, "Optical_Filter")) obs_filter = header.get('FILTER', 'w') etree.SubElement(optical_filter, etree.QName(img_ns, "filter_name")).text = obs_filter obs_filter_bwidth = map_filter_to_bandwidth(obs_filter) obs_filter_bwidth_str = "{:.1f}".format(obs_filter_bwidth.value) obs_filter_bwidth_unit = str(obs_filter_bwidth.unit) etree.SubElement(optical_filter, etree.QName(img_ns, "bandwidth"), attrib={ 'unit': obs_filter_bwidth_unit }).text = obs_filter_bwidth_str obs_filter_cwave = map_filter_to_wavelength(obs_filter) obs_filter_cwave_str = "{:.1f}".format(obs_filter_cwave.value) obs_filter_cwave_unit = str(obs_filter_cwave.unit) etree.SubElement(optical_filter, etree.QName(img_ns, "center_filter_wavelength"), attrib={ 'unit': obs_filter_cwave_unit }).text = obs_filter_cwave_str return optical_filter
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
def fix_namespaces(self): """This method should be called when then namespace map is not correct. It will clone the tree, ensuring all nodes have the proper namespace prefixes """ original_tree = self.element_tree etree.register_namespace('auc', BUILDINGSYNC_URI) # only necessary because we are temporarily allowing the import of files # without xsi:schemaLocation # TODO: consider removing once all files have explicit versions etree.register_namespace('xsi', 'http://www.w3.org/2001/XMLSchema-instance') self.init_tree(version=self.version) new_root = self.element_tree.getroot() original_root = original_tree.getroot() def clone_subtree(original, new): for child in original.iterchildren(): new_child = etree.Element(child.tag) # update text new_child.text = child.text # update attributes for attr, val in child.items(): new_child.set(attr, val) new.append(new_child) clone_subtree(child, new_child) clone_subtree(original_root, new_root)
def __init__(self, dag_id, timestamp): etree.register_namespace("oai", "http://www.openarchives.org/OAI/2.0/") etree.register_namespace("marc21", "http://www.loc.gov/MARC21/slim") self.root = etree.Element( "{http://www.openarchives.org/OAI/2.0/}collection") self.root.attrib["dag-id"] = dag_id self.root.attrib["dag-timestamp"] = timestamp
def mergeProfiles(self, defaultProfiles, customProfiles, outputProfiles): defaultProfilesDoc = etree.parse(defaultProfiles) customProfilesDoc = etree.parse(customProfiles) PROFILES_NAMESPACE = "http://www.bonitasoft.org/ns/profile/6.1" etree.register_namespace('profiles', PROFILES_NAMESPACE) PROFILES = "{%s}" % PROFILES_NAMESPACE profiles = etree.Element(PROFILES + "profiles") # lxml only! root = defaultProfilesDoc.getroot() # print "Found %d default profiles" % len(root.findall("profile", root.nsmap)) for profile in root.findall("profile", root.nsmap): profiles.append(profile) root = customProfilesDoc.getroot() # print "Found %d custom profiles" % len(root.findall("profile", root.nsmap)) for profile in root.findall("profile", root.nsmap): profiles.append(profile) et = etree.ElementTree(profiles) with open(outputProfiles, 'wb') as outputProfilesFile: et.write(outputProfilesFile, pretty_print=True, xml_declaration=True, encoding='utf-8', method="xml") return 200
def generateXMLConfigFile(self): # Register the namespace etree.register_namespace("netzob", PROJECT_NAMESPACE) etree.register_namespace("netzob-common", COMMON_NAMESPACE) # Dump the file root = etree.Element("{" + PROJECT_NAMESPACE + "}project") root.set("id", str(self.getID())) root.set("path", str(self.getPath())) # Warning, changed because of project = Project.createProject(self.netzob.getCurrentWorkspace(), projectName) if isinstance(self.getCreationDate(), types.TupleType): root.set("creation_date", TypeConvertor.pythonDatetime2XSDDatetime(self.getCreationDate()[0])) else: root.set("creation_date", TypeConvertor.pythonDatetime2XSDDatetime(self.getCreationDate())) root.set("name", str(self.getName())) if self.description: root.set("description", str(self.description)) # Save the configuration in it self.getConfiguration().save(root, PROJECT_NAMESPACE) # Save the vocabulary in it self.getVocabulary().save(root, PROJECT_NAMESPACE, COMMON_NAMESPACE) # Save the grammar in it if self.getGrammar() is not None: self.getGrammar().save(root, PROJECT_NAMESPACE) # Save the simulator in it self.getSimulator().save(root, PROJECT_NAMESPACE) return root
def saveConfigFile(self, overrideTraces=[]): """This functions allows to save the current (and only) instance of the Workspace. You can supply a list of traces that should be written on-disk through the `overrideTraces` variable. This allows to override specific traces that where modified. :param overrideTraces: a list of trace identifiers that should be written on-disk, even if they already exists. """ workspaceFile = os.path.join(self.path, Workspace.CONFIGURATION_FILENAME) logging.info("Save the config file of the workspace {0} in {1}".format(self.getName(), workspaceFile)) # Register the namespace etree.register_namespace('netzob', WORKSPACE_NAMESPACE) etree.register_namespace('netzob-common', COMMON_NAMESPACE) # Dump the file root = etree.Element("{" + WORKSPACE_NAMESPACE + "}workspace") root.set("creation_date", TypeConvertor.pythonDatetime2XSDDatetime(self.getCreationDate())) root.set("name", str(self.getName())) xmlWorkspaceConfig = etree.SubElement(root, "{" + WORKSPACE_NAMESPACE + "}configuration") relTracePath = os.path.relpath(self.getPathOfTraces(), self.path) xmlTraces = etree.SubElement(xmlWorkspaceConfig, "{" + WORKSPACE_NAMESPACE + "}traces") xmlTraces.text = str(self.getPathOfTraces()) xmlLogging = etree.SubElement(xmlWorkspaceConfig, "{" + WORKSPACE_NAMESPACE + "}logging") xmlLogging.text = str(self.getPathOfLogging()) xmlPrototypes = etree.SubElement(xmlWorkspaceConfig, "{" + WORKSPACE_NAMESPACE + "}prototypes") xmlPrototypes.text = str(self.getPathOfPrototypes()) xmlPrototypes = etree.SubElement(xmlWorkspaceConfig, "{" + WORKSPACE_NAMESPACE + "}enable_bug_reporting") xmlPrototypes.text = str(self.enableBugReporting).lower() xmlWorkspaceProjects = etree.SubElement(root, "{" + WORKSPACE_NAMESPACE + "}projects") for projectPath in self.getProjectsPath(): xmlProject = etree.SubElement(xmlWorkspaceProjects, "{" + WORKSPACE_NAMESPACE + "}project") xmlProject.set("path", projectPath) xmlWorkspaceImported = etree.SubElement(root, "{" + WORKSPACE_NAMESPACE + "}traces") for importedTrace in self.getImportedTraces(): # overrideTraces variable contains the list of # ImportedTraces that should be overriden. This is useful # in case of message removal for example. forceOverride = (importedTrace.id in overrideTraces) importedTrace.save(xmlWorkspaceImported, WORKSPACE_NAMESPACE, COMMON_NAMESPACE, os.path.join(self.path, self.getPathOfTraces()), forceOverride) xmlWorkspaceFunctions = etree.SubElement(root, "{" + WORKSPACE_NAMESPACE + "}functions") for function in self.getCustomFunctions(): function.save(xmlWorkspaceFunctions, WORKSPACE_NAMESPACE) tree = ElementTree(root) tree.write(workspaceFile, pretty_print=True)
def write_to_radio_spot_order_xml(output_xml_file): tree = ET.ElementTree(root) ET.register_namespace('tvb',"http://www.AAAA.org/schemas/spotTV") ET.register_namespace('tvb-tp',"http://www.AAAA.org/schemas/TVBGeneralTypes") #ET.register_namespace('',"http://www.AAAA.org/schemas/spotTVCableProposal") # only needed with xml.etree.ElementTree package tree.write(output_xml_file, encoding="utf-8", xml_declaration=True, pretty_print=True) print("Radio Spot Order XML has been saved to {}".format(output_xml_file))
def _write_xml(self, eaxs_file, tagged_eaxs_file, tagged_messages, global_id): """ Writes @tagged_eaxs_file as an XML file. Args: - eaxs_file (str): The filepath for the EAXS file. - tagged_eaxs_file (str): The filepath to which the tagged EAXS document will be written. - tagged_messages (generator): The tagged message tuple as returned by self._get_tagged_messages(). - global_id (str): The value of self._get_global_id(@eaxs_file). Returns: list: The return value. The message indexes for messages that failed to finish the tagging process. Raises: - FileExistsError: If @tagged_eaxs_file already exists. """ # raise error if @tagged_eaxs_file already exists. if os.path.isfile(tagged_eaxs_file): err = "Destination file '{}' already exists.".format( tagged_eaxs_file) self.logger.error(err) raise FileExistsError(err) # create placeholder for untagged messages. untagged_messages = [] # open new @tagged_eaxs_file. with etree.xmlfile(tagged_eaxs_file, encoding=self.charset, close=True, buffered=self.buffered) as xfile: # write XML header to @xfile; register namespace information. xfile.write_declaration() etree.register_namespace(self.ncdcr_prefix, self.ncdcr_uri) # write root <Account> element; append tagged <Message> elements. account_tag = "{ns}:Account".format(ns=self.ncdcr_prefix) with xfile.element(account_tag, GlobalId=global_id, SourceEAXS=eaxs_file, nsmap=self.ns_map): # write tagged message to file. for message_index, message_id, tagged_message in tagged_messages: # if message wasn't tagged, append index to @untagged_messages. if tagged_message is None: untagged_messages.append(message_index) # otherwise, write message. else: xfile.write(tagged_message) tagged_message.clear() return untagged_messages
def create_geometry(filename, nsmap): geom_ns = nsmap['PDS4::GEOM']['namespace'] etree.register_namespace("geom", geom_ns) geometry = etree.Element(etree.QName(geom_ns, "Geometry")) return geometry
def __init__(self, filename, pretty_xml=True, data_format="HDF"): from lxml import etree as ET assert data_format in [ "XML", "Binary", "HDF" ], ("Unknown XDMF data format " "'{}' (use 'XML', 'Binary', or 'HDF'.)".format(data_format)) self.filename = filename self.data_format = data_format self.data_counter = 0 self.pretty_xml = pretty_xml self.xdmf_file = ET.Element("Xdmf", Version="3.0") self.domain = ET.SubElement(self.xdmf_file, "Domain") self.collection = ET.SubElement( self.domain, "Grid", Name="TimeSeries_meshio", GridType="Collection", CollectionType="Temporal", ) ET.register_namespace("xi", "https://www.w3.org/2001/XInclude/") self.has_mesh = False self.mesh_name = None
def get_parser(): etree.register_namespace("xi", "http://www.w3.org/2001/XInclude") schema_root = etree.parse( os.path.join(os.path.dirname(__file__), 'share', 'pddoc.xsd')).getroot() schema = etree.XMLSchema(schema_root) return etree.XMLParser(schema=schema)
def to_etree(self, source): etree.register_namespace("junos", NS_JUNOS) return dict_2_etree({ "data": { "configuration": { XML_NS: 'http://xml.juniper.net/xnm/1.1/xnm', XML_ATTRIBUTES: { "xmlns": "http://xml.juniper.net/xnm/1.1/xnm", "{" + NS_JUNOS + "}commit-seconds": "1411928899", "{" + NS_JUNOS + "}commit-localtime": "2014-09-28 14:28:19 EDT", "{" + NS_JUNOS + "}commit-user": "******" }, "interfaces": [{ "interface": self.interface_to_etree(port) } for port in self.configurations[source].ports], "protocols": extract_protocols(self.configurations[source]), "vlans": [{ "vlan": vlan_to_etree(vlan) } for vlan in self.configurations[source].vlans] } } })
def replace_umeng_channel2(umeng_channel: str): # //title[@lang='eng'] try: print('开始替换友盟渠道号' + umeng_channel) namespace_in_attrib_key = '{' + NAMESPACE_MANIFEST + '}' etree.register_namespace('android', NAMESPACE_MANIFEST) success = False manifest_xml = local_config['manifest_xml'] grammar = '//meta-data[@*]' tree = etree.parse(manifest_xml) doc = tree.xpath(grammar) for ele in doc: if ele.attrib[namespace_in_attrib_key + 'name'] == 'UMENG_CHANNEL': ele.attrib[namespace_in_attrib_key + 'value'] = umeng_channel success = True if not success: raise RuntimeError('完成替换友盟渠道号' + umeng_channel) else: tree.write(manifest_xml, pretty_print=True, encoding='utf-8', xml_declaration=True) print('完成替换友盟渠道号' + umeng_channel) except Exception as e: logging.exception(e) raise pass
def _parse_etree(self, root): ns_maec = "http://maec.mitre.org/XMLSchema/maec-package-2" node_ns = etree.QName(root).namespace expected_node_tag = "{%s}MAEC" % (self._namespace) node_tag = root.tag if node_tag != expected_node_tag: if node_ns != ns_maec: raise ValueError( "Cannot set maec property. Expected tag %s but found %s" % (expected_node_tag, node_tag) ) # attempt to cast etree.register_namespace(self._xml_ns_prefix, self._namespace) root.tag = expected_node_tag self.__input_namespaces__ = dict( (ns, alias) for alias, ns in root.nsmap.iteritems() ) try: schemaloc = stix.utils.parser.get_schemaloc_pairs(root) self.__input_schemalocations__ = dict(schemaloc) except KeyError: self.__input_schemalocations__ = {}
def __init__(self, filename, mesh, pretty_xml=True, data_format="HDF"): from lxml import etree as ET assert data_format in [ "XML", "Binary", "HDF" ], ("Unknown XDMF data format " "'{}' (use 'XML', 'Binary', or 'HDF'.)".format(data_format)) self.filename = filename self.data_format = data_format self.data_counter = 0 if data_format == "HDF": import h5py self.h5_filename = os.path.splitext(self.filename)[0] + ".h5" self.h5_file = h5py.File(self.h5_filename, "w") xdmf_file = ET.Element("Xdmf", Version="3.0") domain = ET.SubElement(xdmf_file, "Domain") grid = ET.SubElement(domain, "Grid", Name="Grid") self.points(grid, mesh.points) self.cells(mesh.cells, grid) self.point_data(mesh.point_data, grid) self.cell_data(mesh.cell_data, grid) ET.register_namespace("xi", "https://www.w3.org/2001/XInclude/") write_xml(filename, xdmf_file, pretty_xml) return
def check_xml(xml_func, test_wcs, expected): etree.register_namespace('caom2', 'http://www.opencadc.org/caom2/xml/v2.3') parent_element = etree.Element( '{http://www.opencadc.org/caom2/xml/v2.3}import') xml_func(test_wcs, parent_element) tree = etree.ElementTree(parent_element) result = etree.tostring(tree, encoding='unicode', pretty_print=True) assert result == expected, result
def read_xml_file(xml_path, namespace_dict=None, remove_comments=False): parser = etree.XMLParser(remove_comments=remove_comments) tree = etree.parse(xml_path, parser=parser) etree.set_default_parser(parser) if namespace_dict: for prefix, uri in namespace_dict.items(): etree.register_namespace(prefix, uri) return tree
def parseElements(filename, namespace, types): ET.register_namespace("ms", "http://www.meta-share.org/OMTD-SHARE_XMLSchema") ET.register_namespace("xs", "http://www.w3.org/2001/XMLSchema") # ET.register_namespace("","http://www.meta-share.org/OMTD-SHARE_XMLSchema") tree = ET.parse(filename) root = tree.getroot() nodes = root.xpath(".//xs:documentation/../..", namespaces=namespace) for node in nodes: if 'name' in node.attrib: nodeName = node.attrib['name'] thisDesLabel = {} minOccurs = 1 if 'minOccurs' in node.attrib: minOccurs = node.attrib['minOccurs'] if minOccurs == 1: thisDesLabel['mandatory'] = 'true' else: thisDesLabel['mandatory'] = 'false' doc = node.xpath('.//xs:documentation', namespaces=namespace) thisDesLabel['desc'] = doc[0].text label = node.xpath('.//label', namespaces=namespace) if len(label) > 0: thisDesLabel['label'] = label[0].text else: thisDesLabel['label'] = None recommended = node.xpath('.//recommended', namespaces=namespace) if len(recommended) > 0: thisDesLabel['recommended'] = recommended[0].text else: thisDesLabel['recommended'] = None if nodeName in types: if types[nodeName]['desc'] is None: if doc[0].text != None: types[nodeName]['desc'] = doc[0].text print( '[+] ' + nodeName + ' found duplicate definition with Description (Replacing...) ' ) else: print( '[-] ' + nodeName + ' found duplicate definition with no Description (Ignoring...)' ) else: print( '[-] ' + nodeName + ' found duplicate definition (Keeping first and ignoring rest...) ' ) types[nodeName] = thisDesLabel return types
def __init__(self, name): etree.register_namespace("xi", "http://www.w3.org/2001/XInclude") self._name = name self._lib = etree.Element("library", version="1.0", name=name, nsmap=self.NSMAP) self._cats = {} self._cat_entries = {} self._authors = {} self._version = "" self._search_paths = []
def test_write(): ET.register_namespace("ns", vsq4_namespace) ET.register_namespace("xsi", vsq4_xsi) root = read_vsqx_root(base_path) vsP = extract_vsPart(root) add_cc(vsP, 360, "P", 24) add_note(vsP, 0, 960, "か", "k a") print(type(root)) write_xml(root, test_path)
def add_skos_namespace(old_root, skos_namespace): if skos_namespace is not None: etree.register_namespace('skos', skos_namespace) root = copy.deepcopy(old_root) else: root = old_root doc = root.getroottree() return doc, root
def main(): mydir = os.path.dirname(__file__) prjxray_db = os.path.abspath( os.path.join(mydir, "..", "..", "third_party", "prjxray-db") ) db_types = prjxray.db.get_available_databases(prjxray_db) parser = argparse.ArgumentParser( description=__doc__, fromfile_prefix_chars='@', prefix_chars='-~' ) parser.add_argument( '--part', choices=[os.path.basename(db_type) for db_type in db_types], help="""Project X-Ray database to use.""" ) parser.add_argument('--tile', help="""Tile to generate for""") parser.add_argument( '--tiles-directory', help="""Diretory where tiles are defined""" ) parser.add_argument( '--equivalent-sites', help= """Comma separated list of equivalent sites that can be placed in this tile.""", ) parser.add_argument( '--pin-prefix', help= """Comma separated list of prefix translation pairs for equivalent tiles.""", ) parser.add_argument( '--output-tile', nargs='?', type=argparse.FileType('w'), default=sys.stdout, help="""File to write the output too.""" ) parser.add_argument( '--pin_assignments', required=True, type=argparse.FileType('r') ) parser.add_argument('--priority', action='store_true') args = parser.parse_args() ET.register_namespace('xi', XI_URL) import_physical_tile(args)
def _write_xml(self, eaxs_file, tagged_eaxs_file, tagged_messages, global_id): """ Writes @tagged_eaxs_file as an XML file. Args: - eaxs_file (str): The filepath for the EAXS file. - tagged_eaxs_file (str): The filepath to which the tagged EAXS document will be written. - tagged_messages (generator): The tagged message tuple as returned by self._get_tagged_messages(). - global_id (str): The value of self._get_global_id(@eaxs_file). Returns: list: The return value. The message indexes for messages that failed to finish the tagging process. Raises: - FileExistsError: If @tagged_eaxs_file already exists. """ # raise error if @tagged_eaxs_file already exists. if os.path.isfile(tagged_eaxs_file): err = "Destination file '{}' already exists.".format(tagged_eaxs_file) self.logger.error(err) raise FileExistsError(err) # create placeholder for untagged messages. untagged_messages = [] # open new @tagged_eaxs_file. with etree.xmlfile(tagged_eaxs_file, encoding=self.charset, close=True, buffered=self.buffered) as xfile: # write XML header to @xfile; register namespace information. xfile.write_declaration() etree.register_namespace(self.ncdcr_prefix, self.ncdcr_uri) # write root <Account> element; append tagged <Message> elements. account_tag = "{ns}:Account".format(ns=self.ncdcr_prefix) with xfile.element(account_tag, GlobalId=global_id, SourceEAXS=eaxs_file, nsmap=self.ns_map): # write tagged message to file. for message_index, message_id, tagged_message in tagged_messages: # if message wasn't tagged, append index to @untagged_messages. if tagged_message is None: untagged_messages.append(message_index) # otherwise, write message. else: xfile.write(tagged_message) tagged_message.clear() return untagged_messages
def etreeRegister(self): """ Register all namespace URIs in etree. :note: In etree this is a global setting which is problematic because it is shared. Take care to override the namespaces every time the parser needs them. """ for ( uri, prefixes ) in self.uri2Prefixes.items(): for prefix in prefixes: etree.register_namespace(prefix, uri)
def _cast_maec(self, node): ns_maec = "http://maec.mitre.org/XMLSchema/maec-package-2" node_ns = etree.QName(node).namespace if node_ns == ns_maec: etree.register_namespace(self._xml_ns_prefix, self._namespace) node.tag = self._TAG_MAEC else: error = "Cannot set maec. Expected tag '{0}' found '{1}'." error = error.format(self._TAG_MAEC, node.tag) raise ValueError(error)
def _cast_ioc(self, node): ns_ioc = "http://schemas.mandiant.com/2010/ioc" node_ns = etree.QName(node).namespace if node_ns == ns_ioc: etree.register_namespace(self._xml_ns_prefix, self._namespace) node.tag = self._TAG_IOC else: error = "Cannot set ioc. Expected tag '{0}' found '{1}'." error = error.format(self._TAG_IOC, node.tag) raise ValueError(error)
def write_config_file(self): etree.register_namespace("config", "http://spfeopentoolkit.org/ns/spfe-ot/config") # Write the spfe environment variables to the config file. os.makedirs(self.content_set_config_dir, exist_ok=True) config_file = copy.copy(self.config) for structures in config_file.findall("*//{http://spfeopentoolkit.org/ns/spfe-ot/config}structures"): structures.getparent().remove(structures) for scripts in config_file.findall("*//{http://spfeopentoolkit.org/ns/spfe-ot/config}scripts"): scripts.getparent().remove(scripts) etree.ElementTree(config_file).write( self.content_set_config_dir + "/spfe-config.xml", xml_declaration=True, encoding="utf-8" )
def getXMLDefinition(self): # Register the namespace etree.register_namespace('netzob', PROJECT_NAMESPACE) etree.register_namespace('netzob-common', COMMON_NAMESPACE) # create the file root = etree.Element("{" + NAMESPACE + "}netzob") root.set("project", str(self.getProject().getName())) self.save(root, PROJECT_NAMESPACE, COMMON_NAMESPACE) tree = ElementTree(root) result = etree.tostring(tree, pretty_print=True) return result
def __str__(self): # # need to register the ome namespace because BioFormats expects # that namespace to be the default or to be explicitly named "ome" # for ns_key in ["ome", "sa", "spw"]: ns = self.ns.get(ns_key) or NS_DEFAULT.format(ns_key=ns_key) ElementTree.register_namespace(ns_key, ns) ElementTree.register_namespace("om", NS_ORIGINAL_METADATA) #result = StringIO() #ElementTree.ElementTree(self.root_node).write(result, # encoding=uenc, # method="xml") #return result.getvalue().encode(uenc) root = ElementTree.ElementTree(self.root_node) return ElementTree.tostring(root).decode()
def genera(self) : xsiNs = 'http://www.w3.org/2001/XMLSchema-instance' xsi = '{'+xsiNs +'}' schema = 'SolicitudesRealizadas_v1.0.xsd' etree.register_namespace('xsi', xsiNs) root = self.element(None, 'MensajeSolicitudesRealizadas') root.attrib[xsi+'noNamespaceSchemaLocation'] = schema self.generateHeader(root) self.generateRequestSummaries(root) return etree.tostring( root, pretty_print=True, xml_declaration=True, encoding='utf-8', method="xml", )
def register_namespace(self, prefix, uri): """Registers a namespace,, making it available for use when adding subsequent fields to the entry. Registration will also affect the XML export, adding in the xmlns:prefix="url" attribute when required.""" try: etree.register_namespace(prefix, uri) except AttributeError as e: # the etree implementation we're using doesn't support register_namespace # (probably lxml) pass self.add_ns.append(prefix) if prefix not in NS.keys(): NS[prefix] = "{%s}%%s" % uri # we also have to handle namespaces internally, for etree implementations which # don't support register_namespace if prefix not in self.nsmap.keys(): self.nsmap[prefix] = uri
def __do_propfind(self, request, path): ''' Process PROPFIND WebDAV request. @return: HTTP response: - 207 - ok, - 403 - Depth=infinite, - 404 - Not found ''' #wdp.util.LOG('%s.%s.propfind: "%s"', __name__, self.__class__.__name__, path) __name = 'PROPFIND' self.__log(__name, '"%s"', path) depth = request.META.get('HTTP_DEPTH', None) resource = self.__ds.get_child(path) if (resource): # found # 0. prepare: props, response props = set() body = request.read() if (len(body)): dom = etree.fromstring(body) ##wdp.util.LOG('PROPFIND request:') ##wdp.util.LOG(wdp.util.pprintxml(dom)) for i in list(list(dom)[0]): # lxml.etree._Element (base=None, nsmap={'D': 'DAV:'}, prefix='D', tag='{DAV:}tagname' props.add(i.tag) etree.register_namespace('D', 'DAV:') multistatus = etree.Element('{DAV:}multistatus') # 1. root root_href = request.get_full_path() self.__fill_prop_helper(multistatus, props.copy(), resource, root_href) # 2. process deps if ((depth == '1') and (resource.is_collection())): for child in resource.get_children(): href = os.path.join(root_href, child) member = resource.get_child(child) if (member): if (member.is_collection()): href += '/' self.__fill_prop_helper(multistatus, props.copy(), member, href) # 3. flush ##wdp.util.LOG('PROPFIND response:') ##wdp.util.LOG(wdp.util.pprintxml(multistatus)) return wdp.hr.http_207(etree.tostring(multistatus, pretty_print=False, encoding='utf-8', xml_declaration=True)) else: self.__log(__name, '404 (not found)') return wdp.hr.http_404(path)
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()
def parse(self, inputstring, document): self.setup_parse(inputstring, document) # This is a global setting in etree which is problematic because it is # shared. However, this should work since it is overridden every time # before it is used. [ etree.register_namespace(prefix, uri) for ( uri, prefix ) in self.ns2Prefix.items() ] inDoc = etree.fromstring(inputstring) self.walk(inDoc, self.visitorClass(self, document)) self.finish_parse()
def merge_strings_files(overlay): """ 将指定的资源按照语言合并到一个xml文件中,方便写入数据库 将资源文件按照语言,例如中文的就全部合并到values-zh-rCN目录下的 strings.xml文件中 """ trees = {} ET.register_namespace('xliff', "urn:oasis:names:tc:xliff:document:1.2") files = get_strings_files(overlay) for f in files: lang = get_lang_in_dir(f) xml_tree = ET.parse(f) if lang in trees: root = trees[lang].getroot() for child in xml_tree.getroot(): root.append(child) else: trees[lang] = xml_tree return trees
def parse_xml(path): if not os.path.exists(path): logging.error("File not exists: \"%s\"", path) return None try: NSMAP = {'xi': "http://www.w3.org/2001/XInclude"} etree.register_namespace("xi", "http://www.w3.org/2001/XInclude") xml = etree.parse(path, get_parser()) xml.xinclude() except etree.XMLSyntaxError as e: logging.error("XML syntax error:\n \"%s\"\n\twhile parsing file: \"%s\"", e, path) return None pddoc = xml.getroot() for obj in pddoc.findall('object'): fix_section_order(obj) return xml
def to_etree(self, source): etree.register_namespace("junos", NS_JUNOS) return dict_2_etree({ "data": { "configuration": { XML_NS: 'http://xml.juniper.net/xnm/1.1/xnm', XML_ATTRIBUTES: { "xmlns":"http://xml.juniper.net/xnm/1.1/xnm", "{" + NS_JUNOS + "}commit-seconds": "1411928899", "{" + NS_JUNOS + "}commit-localtime": "2014-09-28 14:28:19 EDT", "{" + NS_JUNOS + "}commit-user": "******" }, "interfaces": [{"interface": self.interface_to_etree(port)} for port in self.configurations[source].ports], "protocols": extract_protocols(self.configurations[source]), "vlans": [{"vlan": vlan_to_etree(vlan)} for vlan in self.configurations[source].vlans] } } })
def to_etree(self, source): etree.register_namespace("junos", NS_JUNOS) configuration = { XML_NS: 'http://xml.juniper.net/xnm/1.1/xnm', XML_ATTRIBUTES: { "xmlns":"http://xml.juniper.net/xnm/1.1/xnm", "{" + NS_JUNOS + "}commit-seconds": "1411928899", "{" + NS_JUNOS + "}commit-localtime": "2014-09-28 14:28:19 EDT", "{" + NS_JUNOS + "}commit-user": "******" } } _add_if_not_empty(configuration, "interfaces", self._extract_interfaces(self.configurations[source])) _add_if_not_empty(configuration, "protocols", extract_protocols(self.configurations[source])) _add_if_not_empty(configuration, "vlans", [{"vlan": vlan_to_etree(vlan)} for vlan in self.configurations[source].vlans]) return dict_2_etree({"data": {"configuration": configuration}})
def setTitles(self, graph_title, x_name, y_name): """ to set Title in xml file: graph title, X title, Y title, Graph Name """ ns = {"xmlns:xsi": self.xsi, "xmlns:xsd": self.xsd} for attr, uri in ns.items(): etree.register_namespace(attr.split(":")[1], uri) self.root = etree.Element("GraphPlotData", {etree.QName(self.xsi, "noNamespaceSchemaLocation"): etree.QName(self.xsd)}) # put `**ns))` if xsi, xsd are unused title = etree.SubElement(self.root, "Title") title.text = graph_title axes = etree.SubElement(self.root, "Axes") x = etree.SubElement(axes, "X") x.set("type", "linear") x_title = etree.SubElement(x, "Title") x_title.text = x_name y = etree.SubElement(axes, "Y") y.set("type", "linear") y_title = etree.SubElement(y, "Title") y_title.text = y_name
def main(): etree.register_namespace("xliff", "urn:oasis:names:tc:xliff:document:1.2") cur_dir = cur_file = "" with open(translated_text, mode="r", encoding="utf-16-le") as f: f.seek(2) #skip BOM reader = csv.reader(f, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL) #read_one(f) state = 0 vocabulary = {} for row in reader: #print(row[0]) id, en, zh, content, *remain = row if state < 2: if state == 0: cur_dir = row[0] if state == 1: cur_file = row[0] state += 1 continue if len(id) == 0: # end of a translation section #print(os.path.join(cur_dir, cur_file)) inpath = os.path.join(orig_root,cur_dir, "values", cur_file) refpath = os.path.join(orig_root,cur_dir, "values-es", cur_file) outpath = os.path.join(out_root,cur_dir, "values-es", cur_file) print(inpath) print(outpath) if os.path.exists(refpath): partial_translate(inpath, refpath, outpath, vocabulary) else: full_translate(inpath, outpath, vocabulary) ''' Clear states ''' state = 0 vocabulary = {} print() elif len(content) == 0: print(id + " has no content") else: vocabulary[id] = content
def PROPPATCH(request, path): ''' @param path:str - 1. '', 2. 'ID/', 3. 'ID/filename.ext' ''' ok, file, filename = __url2path(path) if ((ok) and (file) and (filename)): etree.register_namespace('D', 'DAV:') etree.register_namespace('M', 'urn:schemas-microsoft-com:') etree.register_namespace('A', 'http://apache.org/dav/props/') # 1. prepare response root = etree.SubElement(etree.Element('{DAV:}multistatus'), '{DAV:}response') etree.SubElement(root, '{DAV:}href').text = request.get_full_path() propstat = etree.SubElement(root, '{DAV:}propstat') etree.SubElement(propstat, '{DAV:}status').text = 'HTTP/1.1 200 OK' prop = etree.SubElement(propstat, '{DAV:}prop') # 2. parse request body = request.read() dom = etree.fromstring(body) for i in list(list(list(dom)[0])[0]): # 2. fill response - FAKE!!! etree.SubElement(prop, i.tag) # 4. finish response content = etree.tostring(root, pretty_print=False, encoding='utf-8', xml_declaration=True) response = HttpResponse(content, status = 207, mimetype='text/xml; charset="utf-8"') response['Content-Length'] = len(content) return response raise Http404
def ioc(self, value): if value is None: self._ioc = None return elif isinstance(value, etree._ElementTree): tree = value elif isinstance(value, etree._Element): tree = etree.ElementTree(value) else: raise ValueError('ioc must be instance of lxml.etree._Element ' 'or lxml.etree._ElementTree') root = tree.getroot() expected_node_tag = "{%s}ioc" % (self._namespace) if root.tag != expected_node_tag: ns_ioc = "http://schemas.mandiant.com/2010/ioc" node_ns = etree.QName(root).namespace if node_ns == ns_ioc: # attempt to cast etree.register_namespace(self._xml_ns_prefix, self._namespace) root.tag = expected_node_tag else: raise ValueError( "Cannot set ioc property. Expected tag %s found %s" % (expected_node_tag, root.tag) ) self.__input_namespaces__ = {} for alias,ns in root.nsmap.iteritems(): self.__input_namespaces__[ns] = alias try: schemaloc = stix.utils.parser.get_schemaloc_pairs(root) self.__input_schemalocations__ = dict(schemaloc) except KeyError: self.__input_schemalocations__ = {} self._ioc = tree