def main(): parser = optparse.OptionParser() parser.add_option('-d', '--directory', dest="dir") parser.add_option('-p', '--prefix', dest="prefix") (options, args) = parser.parse_args() if not options.dir: usage() parser.error("dir argument not given") return names = [] for root, dirs, files in os.walk(options.dir, topdown=False): for filename in files: if not filename.endswith(".fzp"): continue fzpFilename = os.path.join(root, filename) try: dom = xml.dom.minidom.parse(fzpFilename) except xml.parsers.expat.ExpatError, err: print str(err), fzpFilename continue fzp = dom.documentElement properties = fzp.getElementsByTagName("property") for property in properties: if property.getAttribute("name") == 'family': value = getText(property.childNodes) if not value in names: names.append(value) if options.prefix != None: for node in property.childNodes: if node.nodeType == node.TEXT_NODE: if not (options.prefix.lower() in node.data.lower()): node.data = options.prefix + " " + node.data outfile = open(fzpFilename, 'wb') s = dom.toxml("UTF-8") outfile.write(s) outfile.close() break break
def main(): parser = optparse.OptionParser() parser.add_option('-d', '--directory', dest="dir" ) parser.add_option('-p', '--prefix', dest="prefix" ) (options, args) = parser.parse_args() if not options.dir: usage() parser.error("dir argument not given") return names = [] for root, dirs, files in os.walk(options.dir, topdown=False): for filename in files: if not filename.endswith(".fzp"): continue fzpFilename = os.path.join(root, filename) try: dom = xml.dom.minidom.parse(fzpFilename) except xml.parsers.expat.ExpatError, err: print str(err), fzpFilename continue fzp = dom.documentElement properties = fzp.getElementsByTagName("property") for property in properties: if property.getAttribute("name") == 'family': value = getText(property.childNodes) if not value in names: names.append(value) if options.prefix != None: for node in property.childNodes: if node.nodeType == node.TEXT_NODE: if not (options.prefix.lower() in node.data.lower()): node.data = options.prefix + " " + node.data outfile = open(fzpFilename, 'wb') s = dom.toxml("UTF-8") outfile.write(s) outfile.close() break break
versionNodes = fzp.getElementsByTagName("version") version = None if (versionNodes.length == 0): version = dom.createElement("version") fzp.insertBefore(version, fzp.firstChild) elif (versionNodes.length == 1): txt = "" version = versionNodes.item(0) else: print "multiple version elements in", fzpFilename continue while version.hasChildNodes(): oldChild = version.firstChild version.removeChild(oldChild) oldChild.unlink() vtext = dom.createTextNode("4") version.appendChild(vtext) print "adding version 4 to", fzpFilename outfile = open(fzpFilename, 'wb') s = dom.toxml("UTF-8") outfile.write(s) outfile.flush() outfile.close() if __name__ == "__main__": main()
r = float(c1.getAttribute("r")) cx = float(c1.getAttribute("cx")) cy = float(c1.getAttribute("cy")) np1.setAttribute("d", ''.join(["M", `cx - r - r`, ",", `cy`, " a",`r * 2`, ",", `r * 2`, " ", `0`, " ", `0`, " ", `1`, " ", `r * 4`, ",", `0`])) np2 = dom.createElement("path") g.appendChild(np2) np2.setAttribute("fill", p2.getAttribute("fill")) np2.setAttribute("d", ''.join(["M", `cx + r + r`, ",", `cy`, " a",`r * 2`, ",", `r * 2`, " ", `0`, " ", `1`, " ", `1`, " ", `-r * 4`, ",", `0`])) g.appendChild(c1) p1.unlink() p2.unlink() outfile = open(output, 'wb') s = dom.toxml("UTF-8") s = re.sub('\s*\n\s*\n', '', s) # ghosts of removed (and unlinked) nodes seem to generate newlines, so tighten up the xml outfile.write(s) outfile.flush() outfile.close() if __name__ == "__main__": main()
def prettify(input, output, strict=True, indentString=' ', color=False, encoding=DEFAULT_ENCODING): ''' Converts the input data stream `input` (which must be a file input like object) to `output` (which must be a file output like object) by parsing the stream as XML and outputting "prettified" XML. Prettification involves the following aspects: * Collapsing ignorable whitespace. * Indenting nodes by `indentString`. * Colorizing the output to more easily identify elements if `color` is True or a color specification (see below). * Normalizing attribute rendering. TODO: that should include canonical ordering of attributes... :Parameters: strict : bool, default: true, optional If the input stream cannot be parsed by python's xml.dom.minidom, then if `strict` is True (the default), an exception is raised. If `strict` is False, then the input data is streamed to `output` as-is. indentString : str, default: ' ', optional The indentation to add to the output stream when entering into a sub-element. Note that this indentation is only added if it will remain "ignorable whitespace" according to the XML specification. color : bool, default: false, optional Whether or not to add *terminfo* terminal colorization sequences to add XML syntax highlighting, including element names, attribute names, and other XML syntax characters. encoding : str, default: 'UTF-8', optional Specify the encoding to use when rendering the XML. By default, it uses ``"UTF-8"``. :Returns: True the input stream was successfully converted. False a parsing error occurred and `strict` was False. Exception other errors (such as IOErrors) occurred. ''' data = input.read() try: dom = xml.dom.minidom.parseString(data) except Exception: if strict: raise output.write(data) return False removeIgnorableWhitespace(dom) indentXml(dom, dom.documentElement, indentString) if color: return colorizeXml(dom, output, encoding=encoding, colorspec=color) xout = dom.toxml(encoding=encoding) + b'\n' output.write(re.sub(b'^(<\\?xml[^>]+?>)', b'\\1\n', xout)) return True
def generate_xml(content): dom = xml.dom.minidom.getDOMImplementation().createDocument(None, "pms-export", None) dom.documentElement.appendChild(content) return dom.toxml("utf-8")
def main(): parser = optparse.OptionParser() parser.add_option('-f', '--fzp', dest="fzpdir" ) parser.add_option('-s', '--svg', dest="svgdir" ) (options, args) = parser.parse_args() if not options.fzpdir: usage() parser.error("fzp dir argument not given") return if not options.svgdir: usage() parser.error("svg dir argument not given") return allsvgs = [] lowersvgs = {} for root, dirs, files in os.walk(options.svgdir, topdown=False): for filename in files: if not filename.endswith(".svg"): continue path = os.path.join(root, filename) allsvgs.append(path) lowersvgs[path.lower()] = filename for root, dirs, files in os.walk(options.fzpdir, topdown=False): for filename in files: if not filename.endswith(".fzp"): continue fzpFilename = os.path.join(root, filename) try: dom = xml.dom.minidom.parse(fzpFilename) except xml.parsers.expat.ExpatError, err: print str(err), fzpFilename continue doUpdate = False fzp = dom.documentElement layerss = fzp.getElementsByTagName("layers") for layers in layerss: image = layers.getAttribute("image").replace("/", "\\") if ("dip_" in image) and ("mil_" in image): continue if ("sip_" in image) and ("mil_" in image): continue if ("jumper_" in image) and ("mil_" in image): continue if ("screw_terminal_" in image): continue if ("jumper" in image): continue if ("mystery_" in image): continue if ("LED-" in image): continue if ("axial_lay" in image): continue if ("resistor_" in image): continue if ("generic" in image) and ("header" in image): continue path1 = os.path.join(options.svgdir, "core", image) path2 = os.path.join(options.svgdir, "contrib", image) path3 = os.path.join(options.svgdir, "obsolete", image) if os.path.isfile(path1) or os.path.isfile(path2) or os.path.isfile(path3): for path in [path1, path2, path3]: try: handle = open(path) if not path in allsvgs: print "mismatch", fzpFilename print "\t", path print thing = layers.getAttribute("image").split("/") thing[1] = lowersvgs[path.lower()] layers.setAttribute("image", "/".join(thing)) doUpdate = True except: pass else: print "missing", fzpFilename, image if doUpdate: outfile = open(fzpFilename, 'wb') s = dom.toxml("UTF-8") outfile.write(s) outfile.close()
def testWriteXML(): str = '<?xml version="1.0" ?><a b="c"/>' dom = parseString(str) domstr = dom.toxml() dom.unlink() confirm(str == domstr)
def parseXML(self, configBody): try: dom = xml.dom.minidom.parseString(configBody) # this comes from a C extension to Python, and can't be named any better: except Exception: logging.exception("parse error in XML") return "parse error in XML" oneboxes = dom.getElementsByTagName('onebox') if not oneboxes: logging.info('No onebox modules found') return None # find the stylesheet dir: self.xslDir = self.cfg.getGlobalParam('ENTFRONT_STYLESHEETS_DIR') if not self.xslDir: logging.error("failed to find stylesheet dir") return "failed to find stylesheet dir" xslNames = [] # list of the oneboxes with their own XSL # create for onebox in oneboxes: nameNodes = onebox.getElementsByTagName('name') if not nameNodes: return "failed to find name element" elif len(nameNodes) > 1: return "more than one name element" name = getText(nameNodes[0].childNodes) results = onebox.getElementsByTagName('resultsTemplate') if len(results) > 1: return "more than one 'resultsTemplate' node found in " + name elif results: err = self.processXSL(onebox, name, results) if err: if err[0] != '0': return err else: xslNames.append(name) # Remove resultsTemplate element from config because backend # doesn't understand it. onebox.removeChild(results[0]) # write out a config file without resultsTemplate for the # backend backendFileName = self.cfg.getGlobalParam("ONEBOX_BACKEND_CONFIG") if backendFileName == None: logging.info("failed to find config file") return "1\n%s" % "failed to find config file" logging.info("backend config file is %s" % backendFileName) backendFile = open(backendFileName, "w") if not backendFile: logging.info("can't open " + backendFileName) return "1\n" backendFile.write(dom.toxml(encoding="utf-8")); backendFile.close() # rewrite the master XSL that calls each individual one: custFile = open(self.xslDir + os.sep + custFileName, "w") custFile.write(customerHeader) for name in xslNames: custFile.write(customerImport % name) custFile.write('\n') # in XSL, the imports need to precede the includes: custFile.write(includeDefault) custFile.write(invokeDefault) for name in xslNames: custFile.write(customerInvocation %(name, name, name)) custFile.write(customerTrailer) custFile.close() # touch each frontend stylesheet that includes any oneboxes, # so the file watcher will notice: for frontend in dom.getElementsByTagName("Frontend"): if frontend.attributes: name = frontend.attributes["name"] if name: ssName = self.xslDir + os.sep + name.nodeValue if os.path.exists(ssName): os.system("touch " + ssName)
domTagList = domTAG.getElementsByTagName('tag') domEpisodeList = dom.getElementsByTagName('number') property = 'west germany' tagName = 'country' propertyTags = [ tag for tag in domTagList if tag.firstChild.nodeValue == property ] parentOfTags = [tag.parentNode for tag in propertyTags] qualMovies = [movie.firstChild.firstChild.nodeValue for movie in parentOfTags] for movie in qualMovies: colorEpisode = [ episode.parentNode for episode in domEpisodeList if episode.firstChild.nodeValue == movie ] episodeNode = colorEpisode[0] newElement = dom.createElement(tagName) newText = dom.createTextNode(property) newElement.appendChild(newText) genreElements = episodeNode.getElementsByTagName('genre') episodeNode.insertBefore(newElement, genreElements[0]) with open('episodelist-out.xml', 'w', encoding='utf-8') as f: f.write(dom.toxml('utf-8').decode('utf-8'))