def json2xml(json_data, make_uuid=False): """Convert json data to TextMate compliant xml""" data = json.loads(json_data, object_pairs_hook=collections.OrderedDict) imp = minidom.DOMImplementation() doctype = imp.createDocumentType("plist", "-//Apple Computer//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd") document = imp.createDocument("", "plist", doctype) plist = document.documentElement plist.setAttribute("version", "1.0") document.appendChild(plist) generate_xml_tree(plist, data, document) if make_uuid and len(plist.childNodes) > 0: first_child = plist.childNodes[0] key = create_text_node(document, "key", "uuid") value = create_text_node(document, "string", str(uuid.uuid1())) first_child.appendChild(key) first_child.appendChild(value) return document.toprettyxml(indent=" ", encoding="UTF-8")
def _write_pretty_result_xml_to_file(self, xml, filename): """Writes a nicely formatted XML file with DOCTYPE, and compressed if necessary.""" if self.compress_results: actual_filename = filename + ".bz2" # Use BZ2File directly or our hack for Python 3.2 open_func = bz2.BZ2File if hasattr(bz2.BZ2File, 'writable') else util.BZ2FileHack else: # write content to temp file first to prevent loosing data # in existing file if writing fails actual_filename = filename + ".tmp" open_func = open with io.TextIOWrapper(open_func(actual_filename, 'wb'), encoding='utf-8') as file: rough_string = ET.tostring(xml, encoding='unicode') reparsed = minidom.parseString(rough_string) doctype = minidom.DOMImplementation().createDocumentType( 'result', RESULT_XML_PUBLIC_ID, RESULT_XML_SYSTEM_ID) reparsed.insertBefore(doctype, reparsed.documentElement) reparsed.writexml(file, indent="", addindent=" ", newl="\n", encoding="utf-8") if self.compress_results: # try to delete uncompressed file (would have been overwritten in no-compress-mode) try: os.remove(filename) except OSError: pass self.all_created_files.discard(filename) self.all_created_files.add(actual_filename) else: os.rename(actual_filename, filename) self.all_created_files.add(filename) return filename
def createDocumentType(self, *args, **kwargs): # sometimes cssutils is picked automatically for # xml.dom.getDOMImplementation, so provide an implementation # see (https://web.archive.org/web/20200701035537/ # https://bitbucket.org/cthedot/cssutils/issues/69) import xml.dom.minidom as minidom return minidom.DOMImplementation().createDocumentType(*args, **kwargs)
def save_function(self): """Saves the function, persistent functions only.""" # Create document, with DTD doc_imp = minidom.DOMImplementation() doc_type = doc_imp.createDocumentType( qualifiedName="high_score_list", publicId="", systemId="high_score_list.dtd", ) doc = doc_imp.createDocument(None, "high_score_list", doc_type) # get root element root = doc.getElementsByTagName("high_score_list")[0] # Loop through games for game_name in self.high_scores: high_score_elem = doc.createElement("high_score") # add game_name element game_name_elem = doc.createElement("game_name") game_name_elem.appendChild(doc.createTextNode(game_name)) high_score_elem.appendChild(game_name_elem) # Add date element date_elem = doc.createElement("date") date_elem.appendChild( doc.createTextNode(str(self.high_scores[game_name]["date"]))) high_score_elem.appendChild(date_elem) # add player_name element player_name_elem = doc.createElement("player_name") player_name_elem.appendChild( doc.createTextNode(self.high_scores[game_name]["player"])) high_score_elem.appendChild(player_name_elem) # add score element score_elem = doc.createElement("score") score_elem.appendChild( doc.createTextNode(self.high_scores[game_name]["score"])) high_score_elem.appendChild(score_elem) # Loop through extra data, adding that. for data_var in self.high_scores[game_name]["data"]: data_elem = doc.createElement("data") # Add variable name element var_elem = doc.createElement("var") var_elem.appendChild(doc.createTextNode(data_var)) data_elem.appendChild(var_elem) # Add value name element value_elem = doc.createElement("value") value_elem.appendChild( doc.createTextNode( self.high_scores[game_name]["data"][data_var])) data_elem.appendChild(value_elem) # Add the data element to the high score high_score_elem.appendChild(data_elem) root.appendChild(high_score_elem) # save XML doc.writexml(open("store/high_score_list.xml", "w"), addindent="\t", newl="\r\n")
def convert(filename, manufacturer, subtype, type, state_key): print "Opening fxp preset file", path.abspath(filename) # extract fxp structure f = open(filename, 'rb') fxp = vst2preset.parse(f.read()) f.close() EXPECTED = 'FXP_OPAQUE_CHUNK' if (fxp['fxMagic'] != EXPECTED): print ".fxp preset is not in opaque chunk format {} (but {}), and so can not be converted.".format( EXPECTED, fxp['fxMagic']) return preset_name = path.splitext(filename)[0] # convert data chunk to base64 base64data = b64encode(fxp['data']['chunk']) # create the aupreset dom # set the DOCTYPE imp = minidom.DOMImplementation() doctype = imp.createDocumentType( qualifiedName='plist', publicId="-//Apple//DTD PLIST 1.0//EN", systemId="http://www.apple.com/DTDs/PropertyList-1.0.dtd", ) doc = imp.createDocument(None, 'plist', doctype) # create the plist element nodeList = doc.getElementsByTagName("plist") plist = nodeList.item(0) plist.setAttribute("version", "1.0") dict = doc.createElement("dict") plist.appendChild(dict) # create document nodes add_key_and_value(doc, state_key, base64data, "data", dict) add_key_and_value(doc, "manufacturer", manufacturer, "integer", dict) add_key_and_value(doc, "name", preset_name, "string", dict) add_key_and_value(doc, "subtype", subtype, "integer", dict) add_key_and_value(doc, "type", type, "integer", dict) add_key_and_value(doc, "version", "0", "integer", dict) aupreset_name = preset_name + ".aupreset" f = open(aupreset_name, "wb") f.write(doc.toxml("utf-8")) f.close() print "Created", path.abspath(aupreset_name) print
def xml_to_string(elem, qualified_name=None, public_id=None, system_id=None): """ Return a pretty-printed XML string for the Element. Also allows setting a document type. """ from xml.dom import minidom rough_string = ET.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) if qualified_name: doctype = minidom.DOMImplementation().createDocumentType( qualified_name, public_id, system_id) reparsed.insertBefore(doctype, reparsed.documentElement) return reparsed.toprettyxml(indent=" ")
def write(self, sheetMusic): """ Interface Methode: Jeder SheetMusicOutput muss diese realisieren. Führt den entsprechenden Ausgabevorgang durch und erstellt ausgebene Datau. Parameters ---------- sheetMusic: SheetMusic Returns ------- successful : boolean War die Ausgabe erfolgreich? """ ########Erstelle Test-SheetMusic #self.create_testdata() ########Ausgabe Test-SheetMusic #self.print_ausgabe_sheetMusic() #Übernehme eingehendes sheetMusic self.sheetMusic = sheetMusic # Öffnet neues XML-Dokument und füllt den Header der Datei temp = minidom.DOMImplementation() doctype = temp.createDocumentType( 'score-partwise', "-//Recordare//DTD MusicXML 3.0 Partwise//EN", "http://www.musicxml.org/dtds/partwise.dtd") self.__doc = temp.createDocument(None, 'score-partwise', doctype) #Erstellt root-Element der XML-Datei root = self.__doc.documentElement #Schreibt Headerinformationen in das root-Element self.write_header(root) #Schreibt die part-list in das root-Element self.write_part_list(root) # Schreibt den erzeugten stream in das Xml-Dokument xml_str = self.__doc.toprettyxml(indent=" ") with open(self.__outputPath, "w") as f: #with open("output_mxml.xml", "w") as f: f.write(xml_str) return None
def pretty_xml(xml): ret = ElementTree.tostring(xml) ret = minidom.parseString(ret) imp = minidom.DOMImplementation() doctype = imp.createDocumentType( qualifiedName="hsreplay", publicId="", systemId=SYSTEM_DTD, ) doc = imp.createDocument(None, "HSReplay", doctype) for element in list(ret.documentElement.childNodes): doc.documentElement.appendChild(element) doc.documentElement.setAttribute("version", __version__) ret = doc.toprettyxml(indent="\t") return "\n".join(line for line in ret.split("\n") if line.strip())
def save_to_xml(self): """Saves ReplyMessageList to XML.""" # Create document, with DTD doc_imp = minidom.DOMImplementation() doc_type = doc_imp.createDocumentType( qualifiedName="reply_list", publicId="", systemId="reply_list.dtd", ) doc = doc_imp.createDocument(None, "reply_list", doc_type) # get root element root = doc.getElementsByTagName("reply_list")[0] # Add reply message objects for reply_obj in self.reply_message_list: reply_elem = minidom.parseString(reply_obj.to_xml()).firstChild root.appendChild(reply_elem) # save XML doc.writexml(open("store/reply_list.xml", "w"), addindent="\t", newl="\n")
def __init__(self, version="2.0", binary_version="6.0", afterburner=0, log_all=False, fifo_mode="NO", param_lif=None, param_xml=None): if param_lif is not None: self.parseLif(param_lif) elif param_xml is not None: self.parseXml(param_xml) else: imp = minidom.DOMImplementation() doctype = imp.createDocumentType(qualifiedName="KVASER", publicId="", systemId="") self.document = imp.createDocument(None, 'KVASER', doctype) root = self.document.documentElement self.document.appendChild(root) comment = self.document.createComment("Created with memoConfig.py") root.appendChild(comment) child = self.document.createElement('VERSION') text = self.document.createTextNode(version) child.appendChild(text) root.appendChild(child) child = self.document.createElement('BINARY_VERSION') text = self.document.createTextNode(binary_version) child.appendChild(text) root.appendChild(child) xmlSettings = self.document.createElement('SETTINGS') root.appendChild(xmlSettings) xmlMode = self.document.createElement('MODE') xmlMode.setAttribute('log_all', "YES" if log_all else "NO") xmlMode.setAttribute('fifo_mode', fifo_mode) xmlSettings.appendChild(xmlMode) xmlCanpower = self.document.createElement('CANPOWER') xmlCanpower.setAttribute('timeout', str(afterburner)) xmlSettings.appendChild(xmlCanpower)
def createDocumentType(self, *args, **kwargs): # sometimes css_parser is picked automatically for # xml.dom.getDOMImplementation, so we should provide an implementation # see https://bitbucket.org/cthedot/css_parser/issues/69 import xml.dom.minidom as minidom return minidom.DOMImplementation().createDocumentType(*args, **kwargs)
def __init__(self, xmlpath): self.xmlpath = xmlpath self.dom = minidom.DOMImplementation().createDocument(None, 'root', None) self.root = self.dom.documentElement
def make_xml(products=None): if products: products = products else: products = Product.objects.filter(import_to_rozetka=True) category_list = [] for product in products: if product.import_to_rozetka: [ category_list.append(j) for j in [ i for i in product.category_rozetka.get_ancestors(include_self=True, ascending=False) ] ] categories_list = [i for i in set(category_list)] imp = minidom.DOMImplementation() doctype = imp.createDocumentType( qualifiedName="yml_catalog", publicId="", systemId="shops.dtd", ) doc = minidom.Document() doc.appendChild(doctype) yml_catalog = doc.createElement('yml_catalog') doc.appendChild(yml_catalog) yml_catalog.setAttribute('date', datetime.now().strftime("%Y-%m-%d %H:%M")) shop = doc.createElement('shop') yml_catalog.appendChild(shop) name = doc.createElement('name') name_text = doc.createTextNode('PPF Company') name.appendChild(name_text) shop.appendChild(name) company = doc.createElement('company') company_text = doc.createTextNode('PPF Company inc.') company.appendChild(company_text) shop.appendChild(company) url = doc.createElement('url') url_text = doc.createTextNode(settings.SITE_URL) url.appendChild(url_text) shop.appendChild(url) currencies = doc.createElement('currencies') shop.appendChild(currencies) currency = doc.createElement('currency') currency.setAttribute('id', 'UAH') currency.setAttribute('rate', '1') currencies.appendChild(currency) categories = doc.createElement('categories') shop.appendChild(categories) for cat in categories_list: category = doc.createElement('category') category_text = doc.createTextNode(cat.title) if cat.parent: category.setAttribute('parentId', str(cat.parent.id)) category.setAttribute('id', str(cat.id)) category.appendChild(category_text) categories.appendChild(category) offers = doc.createElement('offers') shop.appendChild(offers) def create_node(node_name, node_value): node = doc.createElement(node_name) node.appendChild(doc.createTextNode(str(node_value))) offer.appendChild(node) for product in products: if product.import_to_rozetka: offer = doc.createElement('offer') offer.setAttribute('id', '{}'.format(product.id)) if product.stock_quantity == 0: offer.setAttribute('available', 'false') else: offer.setAttribute('available', 'true') offers.appendChild(offer) create_node('url', '{}{}'.format(settings.SITE_URL, product.get_absolute_url())) if product.old_price_percent: create_node('price', product.get_old_price()) create_node('price_old', product.get_price_UAH()) else: create_node('price', product.get_price_UAH()) if product.promo_percent: create_node('price_promo', product.get_promo_price()) create_node('currencyId', 'UAH') create_node('categoryId', product.category_rozetka.id) if product.image: create_node('picture', '{}'.format(product.image.url)) for photo in product.get_images(): create_node('picture', '{}'.format(photo.image.url)) create_node('vendor', product.manufacturer.title) create_node('stock_quantity', product.stock_quantity) create_node('name', '{title} ({code})'.format( title=product.title, code=product.code, )) description = doc.createElement('description') cdata = doc.createCDATASection(clear_content(product.text)) description.appendChild(cdata) offer.appendChild(description) # param1 = doc.createElement('param') # param1_text = doc.createTextNode(product.code) # param1.appendChild(param1_text) # param1.setAttribute('name', 'Артикул') # offer.appendChild(param1) for feature in product.parameter_set.filter(is_dop_param_for_rozetka=False): param2 = doc.createElement('param') param2_text = doc.createTextNode(feature.value) param2.appendChild(param2_text) param2.setAttribute('name', feature.parameter) offer.appendChild(param2) dop_parameters = [] for dop_param in product.parameter_set.filter(is_dop_param_for_rozetka=True): dop_parameters.append('{}: {}<br/>'.format(dop_param.parameter, dop_param.value)) param3 = doc.createElement('param') param3.setAttribute('name', 'Дополнительные характеристики') cdata2 = doc.createCDATASection(''.join(dop_parameters)) param3.appendChild(cdata2) offer.appendChild(param3) file_handle = open("rozetka.xml", "w") doc.writexml(file_handle, encoding='UTF-8') file_handle.close()