def startElement(self, name, attrs: AttributesNSImpl): self.parser_path.append(name) xpath = '/' + ('/'.join(self.parser_path)) copy_path = list(self.parser_path) node_name = ('_'.join(self.parser_path)) curr_schema = self.schema.get(xpath) # type: OrderedDict if curr_schema is None: fc_ = FeedColumn( type="TEXT", search_path=xpath, path=copy_path, name=name, display_name=node_name ) curr_schema = self.schema.setdefault(xpath, fc_) if curr_schema: attrs_names = attrs.getNames() if attrs_names: for attr_name in attrs_names: attr_xpath = xpath + "/@" + attr_name attr_node = self.schema.get(attr_xpath) if attr_node is None: fc_ = FeedColumn( type="TEXT", search_path=attr_xpath, path=copy_path, name=attr_name, display_name=node_name + "_" + attr_name ) self.schema.setdefault(attr_xpath, fc_)
def write_binding(self, name, val): assert self._resultStarted attr_vals = { (None, u'name'): unicode(name), } attr_qnames = { (None, u'name'): u'name', } self.writer.startElementNS((SPARQL_XML_NAMESPACE, u'binding'), u'binding', AttributesNSImpl(attr_vals, attr_qnames)) if isinstance(val, URIRef): self.writer.startElementNS((SPARQL_XML_NAMESPACE, u'uri'), u'uri', AttributesNSImpl({}, {})) self.writer.characters(val) self.writer.endElementNS((SPARQL_XML_NAMESPACE, u'uri'), u'uri') elif isinstance(val, BNode): self.writer.startElementNS((SPARQL_XML_NAMESPACE, u'bnode'), u'bnode', AttributesNSImpl({}, {})) self.writer.characters(val) self.writer.endElementNS((SPARQL_XML_NAMESPACE, u'bnode'), u'bnode') elif isinstance(val, Literal): attr_vals = {} attr_qnames = {} if val.language: attr_vals[(XML_NAMESPACE, u'lang')] = val.language attr_qnames[(XML_NAMESPACE, u'lang')] = u"xml:lang" elif val.datatype: attr_vals[(None, u'datatype')] = val.datatype attr_qnames[(None, u'datatype')] = u'datatype' self.writer.startElementNS( (SPARQL_XML_NAMESPACE, u'literal'), u'literal', AttributesNSImpl(attr_vals, attr_qnames)) self.writer.characters(val) self.writer.endElementNS((SPARQL_XML_NAMESPACE, u'literal'), u'literal') else: raise Exception("Unsupported RDF term: %s" % val) self.writer.endElementNS((SPARQL_XML_NAMESPACE, u'binding'), u'binding')
def write_header(self, allvarsL): self.writer.startElementNS( (SPARQL_XML_NAMESPACE, u'head'), u'head', AttributesNSImpl({}, {})) for i in range(0, len(allvarsL)): attr_vals = { (None, u'name'): text_type(allvarsL[i]), } attr_qnames = { (None, u'name'): u'name', } self.writer.startElementNS( (SPARQL_XML_NAMESPACE, u'variable'), u'variable', AttributesNSImpl(attr_vals, attr_qnames)) self.writer.endElementNS((SPARQL_XML_NAMESPACE, u'variable'), u'variable') self.writer.endElementNS((SPARQL_XML_NAMESPACE, u'head'), u'head')
def _attributes(self, **attributes): values, qnames = {}, {} for name, value in attributes.iteritems(): name = unicode(name) ns_name = (None, name) qnames[ns_name] = name values[ns_name] = value return AttributesNSImpl(values, qnames)
def write_header(self, allvarsL): self.writer.startElementNS((SPARQL_XML_NAMESPACE, "head"), "head", AttributesNSImpl({}, {})) for i in range(0, len(allvarsL)): attr_vals = { (None, "name"): str(allvarsL[i]), } attr_qnames = { (None, "name"): "name", } self.writer.startElementNS( (SPARQL_XML_NAMESPACE, "variable"), "variable", AttributesNSImpl(attr_vals, attr_qnames), ) self.writer.endElementNS((SPARQL_XML_NAMESPACE, "variable"), "variable") self.writer.endElementNS((SPARQL_XML_NAMESPACE, "head"), "head")
def write_script (self, src) : attrs = AttributesNSImpl({(NS_MAP['h'], 'type'):'application/x-javascript', (NS_MAP['h'], 'src'):src}, {}); self.xml.startElementNS((NS_MAP['h'], 'script'), None, attrs) self.xml.characters(" ") self.xml.endElementNS((NS_MAP['e'], 'script'), None)
def __init__(self, output, encoding='utf-8'): writer = XMLGenerator(output, encoding) writer.startDocument() writer.startPrefixMapping(u'sparql',SPARQL_XML_NAMESPACE) writer.startPrefixMapping(u'xml', XML_NAMESPACE) writer.startElementNS((SPARQL_XML_NAMESPACE, u'sparql'), u'sparql', AttributesNSImpl({}, {})) self.writer = writer self._output = output self._encoding = encoding
def write_style (self, src) : attrs = AttributesNSImpl({(NS_MAP['h'], 'type'):'text/css', (NS_MAP['h'], 'media'):'screen'}, {}); self.xml.startElementNS((NS_MAP['h'], 'style'), None, attrs) self.xml.characters("@import \"%s\";" % src) self.xml.endElementNS((NS_MAP['e'], 'style'), None)
def start_element(self, qname, attrs={}): name = self.resolve_namespace(qname) attr_vals = OrderedDict() attr_qnames = OrderedDict() for attr_qname, attr_val in attrs.items(): attr_name = self.resolve_namespace(attr_qname) attr_vals[attr_name] = attr_val attr_qnames[attr_name] = attr_qname attrs_ns = AttributesNSImpl(attr_vals, attr_qnames) self._g.startElementNS(name, qname, attrs_ns)
def write_toolbar (self) : tb_attrs = AttributesNSImpl({(NS_MAP['h'], 'class'):'toolbar'}, {}); title_attrs = AttributesNSImpl({(NS_MAP['h'], 'id'):'pageTitle'}, {}); back_attrs = AttributesNSImpl({(NS_MAP['h'], 'id'):'backButton', (NS_MAP['h'], 'class'):'button', (NS_MAP['h'], 'href'):'#'}, {}); self.xml.startElementNS((NS_MAP['h'], 'div'), None, tb_attrs) self.xml.startElementNS((NS_MAP['h'], 'h1'), None, title_attrs) self.xml.endElementNS((NS_MAP['h'], 'h1'), None) self.xml.startElementNS((NS_MAP['h'], 'a'), None, back_attrs) self.xml.endElementNS((NS_MAP['h'], 'a'), None) self.xml.endElementNS((NS_MAP['h'], 'div'), None)
def write_categories(self, subjects): for tag in subjects: attrs = AttributesNSImpl( { (NS_MAP['e'], 'type'): 'name', (NS_MAP['e'], 'content'): tag }, {}) self.xml.startElementNS((NS_MAP['e'], 'category'), None, attrs) self.xml.endElementNS((NS_MAP['e'], 'category'), None)
def __init__(self, output, encoding="utf-8"): writer = XMLGenerator(output, encoding) writer.startDocument() writer.startPrefixMapping("", SPARQL_XML_NAMESPACE) writer.startPrefixMapping("xml", XML_NAMESPACE) writer.startElementNS((SPARQL_XML_NAMESPACE, "sparql"), "sparql", AttributesNSImpl({}, {})) self.writer = writer self._output = output self._encoding = encoding self._results = False
def startTag(self, name, attr={}, body=None, namespace=None): attr_vals = {} attr_keys = {} for key, val in attr.iteritems(): key_tuple = (namespace, key) attr_vals[key_tuple] = val attr_keys[key_tuple] = key attr2 = AttributesNSImpl(attr_vals, attr_keys) self.g.startElementNS((namespace, name), name, attr2) if body: self.g.characters(body) return
def write_results_header(self, orderBy, distinct): attr_vals = { (None, u'ordered'): unicode(orderBy and 'true' or 'false'), (None, u'distinct'): unicode(distinct and 'true' or 'false'), } attr_qnames = { (None, u'ordered'): u'ordered', (None, u'distinct'): u'distinct' } self.writer.startElementNS( (SPARQL_XML_NAMESPACE, u'results'), u'results', AttributesNSImpl(attr_vals, attr_qnames))
def __generate_group(self, name, tagNames): """Generates group with references to allowed element.""" self.__doc.startElementNS((XSD_NS, u'group'), u'xsd:group', AttributesNSImpl({(None, 'name'): name}, {})) self.__doc.startElementNS((XSD_NS, u'choice'), u'xsd:choice', AttributesNSImpl({}, {})) for tagName in tagNames: self.__doc.startElementNS((XSD_NS, u'element'), u'xsd:element', AttributesNSImpl( { (None, 'ref'): ':'.join(tagName), (None, 'minOccurs'): '0', (None, 'maxOccurs'): 'unbounded' }, {})) self.__doc.endElementNS((XSD_NS, u'element'), u'xsd:element') self.__doc.endElementNS((XSD_NS, u'choice'), u'xsd:choice') self.__doc.endElementNS((XSD_NS, u'group'), u'xsd:group')
def write_import(self, file): attr_vals = { (None, 'file'): file, } attr_names = { (None, 'file'): 'file', } attrs = AttributesNSImpl(attr_vals, attr_names) self.file.write(self.indent_level) self.xmlout.startElementNS((None, 'import'), 'import', attrs) self.xmlout.endElementNS((None, 'import'), 'import') self.file.write('\n')
def write_importdir(self, dir): attr_vals = { (None, 'dir'): dir, } attr_names = { (None, 'dir'): 'dir', } attrs = AttributesNSImpl(attr_vals, attr_names) self.file.write(self.indent_level) self.xmlout.startElementNS((None, 'import'), 'import', attrs) self.xmlout.endElementNS((None, 'import'), 'import') self.file.write('\n')
def writeLink(x, namespace, localname, rel, type, href): rel = AttributesNSImpl( { (None, "rel"): rel, (None, "href"): href, (None, "type"): type }, { (None, "rel"): "rel", (None, "href"): "href", (None, "type"): "type" }) x.startElement(namespace, localname, rel) x.endElement()
def __generate_element(self, tagName, className, classInfo, attributeGroups, elementGroup): """Generates an definition of XSD element. @param tagName tuple produced by __parse_tag_name @param className name of widget class @param classInfo dictionary with class information @param attributeGroups array with all attribute groups which this class includes (simply all inheritance chain) @param elementGroup array with all allowed child elements """ self.__doc.startElementNS( (XSD_NS, u'element'), u'xsd:element', AttributesNSImpl({(None, 'name'): tagName[1]}, {})) self.__doc.startElementNS((XSD_NS, u'annotation'), u'xsd:annotation', AttributesNSImpl({}, {})) self.__doc.startElementNS( (XSD_NS, u'documentation'), u'xsd:documentation', AttributesNSImpl({}, {})) self.__doc.characters(classInfo.get('info', '')) self.__doc.endElementNS((XSD_NS, u'documentation'), u'xsd:documentation') self.__doc.endElementNS((XSD_NS, u'annotation'), u'xsd:annotation') self.__doc.startElementNS((XSD_NS, u'complexType'), u'xsd:complexType', AttributesNSImpl({}, {})) #generate references for allowed child elements self.__doc.startElementNS((XSD_NS, u'sequence'), u'xsd:sequence', AttributesNSImpl({}, {})) for group in elementGroup: self.__doc.startElementNS( (XSD_NS, u'group'), u'xsd:group', AttributesNSImpl({(None, 'ref'): ":".join(group)}, {})) self.__doc.endElementNS((XSD_NS, u'group'), u'xsd:group') self.__doc.endElementNS((XSD_NS, u'sequence'), u'xsd:sequence') #generate attribute group for attrGroupName in attributeGroups: #TODO fix namespace of the generated group self.__doc.startElementNS( (XSD_NS, u'attributeGroup'), u'xsd:attributeGroup', AttributesNSImpl({(None, 'ref'): "qx:%s" % attrGroupName}, {})) self.__doc.endElementNS((XSD_NS, u'attributeGroup'), u'xsd:attributeGroup') self.__doc.endElementNS((XSD_NS, u'complexType'), u'xsd:complexType') self.__doc.endElementNS((XSD_NS, u'element'), u'xsd:element')
def __generate_attribute_group(self, className, classInfo): """Generate an attribute group based on given classInfo for each class. Includes class property in group if it's not overriden from base class (in other case it will be added for base class). """ self.__doc.startElementNS( (XSD_NS, u'attributeGroup'), u'xsd:attributeGroup', AttributesNSImpl({(None, 'name'): className}, {})) #generate attrubute group only if class has any properties if classInfo.has_key('properties'): properties = classInfo['properties'] for propName, prop in properties.iteritems(): #include property only if it's not overriden from base class if not prop.get('overriddenFrom'): self.__doc.startElementNS( (XSD_NS, u'attribute'), u'xsd:attribute', AttributesNSImpl({(None, 'name'): propName}, {})) self.__doc.startElementNS((XSD_NS, u'annotation'), u'xsd:annotation', AttributesNSImpl({}, {})) self.__doc.startElementNS((XSD_NS, u'documentation'), u'xsd:documentation', AttributesNSImpl({}, {})) self.__doc.characters(prop.get('info', '')) self.__doc.endElementNS((XSD_NS, u'documentation'), u'xsd:documentation') self.__doc.endElementNS((XSD_NS, u'annotation'), u'xsd:annotation') self.__doc.endElementNS((XSD_NS, u'attribute'), u'xsd:attribute') self.__doc.endElementNS((XSD_NS, u'attributeGroup'), u'xsd:attributeGroup')
def write_codebook(tags, output): output.startElementNS( (None, 'CodeBook'), 'CodeBook', AttributesNSImpl({(None, 'origin'): 'Taguette %s' % __version__}, {(None, 'origin'): 'origin'}), ) output.startElementNS( (None, 'Codes'), 'Codes', AttributesNSImpl({}, {}), ) for tag in tags: guid = uuid.uuid5(TAGUETTE_NAMESPACE, tag.path) guid = str(guid).upper() output.startElementNS( (None, 'Code'), 'Code', AttributesNSImpl( { (None, 'guid'): guid, (None, 'name'): tag.path, (None, 'isCodable'): 'true' }, { (None, 'guid'): 'guid', (None, 'name'): 'name', (None, 'isCodable'): 'isCodable' }), ) output.endElementNS((None, 'Code'), 'Code') output.endElementNS((None, 'Codes'), 'Codes') output.startElementNS( (None, 'Sets'), 'Sets', AttributesNSImpl({}, {}), ) output.endElementNS((None, 'Sets'), 'Sets') output.endElementNS((None, 'CodeBook'), 'CodeBook')
def start_tag(doc, name, attr=None, body=None, namespace=None): """Wrapper to start an xml tag.""" if attr is None: attr = {} attr_vals = {} attr_keys = {} for key, val in attr.iteritems(): key_tuple = (namespace, key) attr_vals[key_tuple] = val attr_keys[key_tuple] = key attr2 = AttributesNSImpl(attr_vals, attr_keys) doc.startElementNS((namespace, name), name, attr2) if body: doc.characters(body)
def write_extref (self, link, title) : pattern = re.compile("\[\[(.*)\]\[(.*)\]\]") matches = pattern.findall(title) if len(matches) : link = matches[0][0] title = matches[0][1] attrs = AttributesNSImpl({(NS_MAP['xlink'], 'href'):link, (NS_MAP['xlink'], 'title'):title}, {}); self.xml.startElementNS((NS_MAP['e'], 'extref'), None, attrs) self.xml.endElementNS((NS_MAP['e'], 'extref'), None)
def _edgePathRef(self, xml, offset): element = self._svgName('use') xml.ignorableWhitespace('\n ') attrs = AttributesNSImpl( { self.XLINK_HREF_ATTR: '#' + self.EDGE_PATH_ID, self.X_ATTR: str(offset) }, { self.XLINK_HREF_ATTR: self.XLINK_PREFIX + ':' + self.XLINK_HREF_ATTR[1], self.X_ATTR: self.X_ATTR[1] }) xml.startElementNS(element, None, attrs) xml.endElementNS(element, None)
def handle_start_tag(self,name,attrs): old_ns={} # Reset ns_map to these values when we leave this element del_ns=[] # Delete these prefixes from ns_map when we leave element # attrs=attrs.copy() Will have to do this if more filters are made # Find declarations, update self.ns_map and self.ns_stack for (a,v) in attrs.items(): if a[:6]=="xmlns:": prefix=a[6:] if string.find(prefix,":")!=-1: self.parser.report_error(1900) #if v=="": # self.parser.report_error(1901) elif a=="xmlns": prefix="" else: continue if self.ns_map.has_key(prefix): old_ns[prefix]=self.ns_map[prefix] if v: self.ns_map[prefix]=v else: del self.ns_map[prefix] if not self.rep_ns_attrs: del attrs[a] self.ns_stack.append((old_ns,del_ns)) # Process elem and attr names cooked_name = self.__process_name(name) ns = cooked_name[0] rawnames = {} for (a,v) in attrs.items(): del attrs[a] aname = self.__process_name(a, is_attr=1) if attrs.has_key(aname): self.parser.report_error(1903) attrs[aname] = v rawnames[aname] = a # Report event self._cont_handler.startElementNS(cooked_name, name, AttributesNSImpl(attrs, rawnames))
def write_layers(self, map): for layer in map.getLayers(): cellgrid = layer.getCellGrid() attr_vals = { (None, 'id'): layer.getId(), (None, 'grid_type'): cellgrid.getType(), (None, 'x_scale'): str(cellgrid.getXScale()), (None, 'y_scale'): str(cellgrid.getYScale()), (None, 'rotation'): str(cellgrid.getRotation()), (None, 'x_offset'): str(cellgrid.getXShift()), (None, 'y_offset'): str(cellgrid.getYShift()), (None, 'z_offset'): str(cellgrid.getZShift()), (None, 'pathing'): self.pathing_val_to_str(layer.getPathingStrategy()), (None, 'transparency'): str(layer.getLayerTransparency()), (None, 'layer_type'): str(self.layer_type_to_str(layer)), (None, 'layer_type_id'): str(layer.getWalkableId()), } attr_names = { (None, 'id'): 'id', (None, 'grid_type'): 'grid_type', (None, 'scaling'): 'scaling', (None, 'rotation'): 'rotation', (None, 'x_offset'): 'x_offset', (None, 'y_offset'): 'y_offset', (None, 'z_offset'): 'z_offset', (None, 'pathing'): 'pathing', (None, 'layer_type'): 'layer_type', (None, 'layer_type_id'): 'layer_type_id', } attrs = AttributesNSImpl(attr_vals, attr_names) self.startElement('layer', attrs) self.write_instances(layer) self.write_lights(layer) self.endElement('layer')
def __start_schema(self): """Generates schema header.""" self.__doc.startPrefixMapping(u'xsd', XSD_NS) self.__doc.startPrefixMapping(u'qx', QX_NS) self.__doc.startPrefixMapping(u'qxt', QXT_NS) shemaattr = AttributesNSImpl( { (None, 'targetNamespace'): "http://www.qxtransformer.org/qooxdoo/0.8", (None, 'elementFormDefault'): 'qualified', (None, 'attributeFormDefault'): 'unqualified' }, {}) self.__doc.startElementNS((XSD_NS, u'schema'), u'xsd:schema', shemaattr)
def write_map(self): assert self.state == self.SModel, "Declaration of <map> not at the top level." attr_vals = { (None, 'id'): self.map.getId(), (None, 'format'): MAPFORMAT, } attr_names = { (None, 'id'): 'id', (None, 'format'): 'format', } attrs = AttributesNSImpl(attr_vals, attr_names) self.startElement('map', attrs) self.state = self.SMap self.write_imports(self.map, self.importList) self.write_layers(self.map) self.write_camera(self.map) self.endElement('map')
def write_camera(self, map): cameralist = map.getCameras() for cam in cameralist: if cam.getLocationRef().getMap().getId() == map.getId(): celldimensions = cam.getCellImageDimensions() viewport = cam.getViewPort() attr_names = { (None, 'id'): 'id', (None, 'zoom'): 'zoom', (None, 'tilt'): 'tile', (None, 'rotation'): 'rotation', (None, 'ref_layer_id'): 'ref_layer_id', (None, 'ref_cell_width'): 'ref_cell_width', (None, 'ref_cell_height'): 'ref_cell_height', } attr_vals = { (None, 'id'): cam.getId(), (None, 'zoom'): str(cam.getZoom()), (None, 'tilt'): str(cam.getTilt()), (None, 'rotation'): str(cam.getRotation()), (None, 'ref_layer_id'): cam.getLocation().getLayer().getId(), (None, 'ref_cell_width'): str(celldimensions.x), (None, 'ref_cell_height'): str(celldimensions.y), } # add a viewport entry if the cam isn't full sized if not (viewport == self.engine.getRenderBackend().getArea()): attr_names[(None, 'viewport')] = 'viewport' attr_vals[(None, 'viewport')] = '%d,%d,%d,%d' % ( viewport.x, viewport.y, viewport.w, viewport.h) colors = cam.getLightingColor() if colors[0] < 1.0 or colors[1] < 1.0 or colors[2] < 1.0: attr_names[(None, 'light_color')] = 'light_color' attr_vals[(None, 'light_color')] = '%f,%f,%f' % ( colors[0], colors[1], colors[2]) attrs = AttributesNSImpl(attr_vals, attr_names) self.startElement('camera', attrs) self.endElement('camera')
def write_html (self) : for prefix, uri in NS_MAP.items() : self.xml.startPrefixMapping(prefix, uri) self.xml.startDocument() lang = {} if self.isset_notempty(self.data, 'language') : lang = AttributesNSImpl({(NS_MAP['x'], 'lang'):self.data['language']}, {}); self.xml.startElementNS((NS_MAP['h'], 'html'), None, lang) self.write_head() self.write_body() self.xml.endElementNS((NS_MAP['h'], 'html'), None) self.xml.endDocument()
def start_tag(doc, name, attr=None, body=None, namespace=None): """Wrapper to start an xml tag.""" if attr is None: attr = {} dct_type = dict elif isinstance(attr, OrderedDict): dct_type = OrderedDict else: dct_type = dict attr_vals = dct_type() attr_keys = dct_type() for key, val in attr.items(): key_tuple = (namespace, key) attr_vals[key_tuple] = val attr_keys[key_tuple] = key attr2 = AttributesNSImpl(attr_vals, attr_keys) doc.startElementNS((namespace, name), name, attr2) if body: doc.characters(body)
def test_nsattrs_wattr(self): attrs = AttributesNSImpl({(ns_uri, "attr") : "val"}, {(ns_uri, "attr") : "ns:attr"}) self.assertEqual(attrs.getLength(), 1) self.assertEqual(attrs.getNames(), [(ns_uri, "attr")]) self.assertEqual(attrs.getQNames(), ["ns:attr"]) self.assertEqual(len(attrs), 1) self.assertTrue((ns_uri, "attr") in attrs) self.assertEqual(list(attrs.keys()), [(ns_uri, "attr")]) self.assertEqual(attrs.get((ns_uri, "attr")), "val") self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val") self.assertEqual(list(attrs.items()), [((ns_uri, "attr"), "val")]) self.assertEqual(list(attrs.values()), ["val"]) self.assertEqual(attrs.getValue((ns_uri, "attr")), "val") self.assertEqual(attrs.getValueByQName("ns:attr"), "val") self.assertEqual(attrs.getNameByQName("ns:attr"), (ns_uri, "attr")) self.assertEqual(attrs[(ns_uri, "attr")], "val") self.assertEqual(attrs.getQNameByName((ns_uri, "attr")), "ns:attr")
def test_nsattrs_wattr(): attrs = AttributesNSImpl({(ns_uri, "attr") : "val"}, {(ns_uri, "attr") : "ns:attr"}) return attrs.getLength() == 1 and \ attrs.getNames() == [(ns_uri, "attr")] and \ attrs.getQNames() == ["ns:attr"] and \ len(attrs) == 1 and \ attrs.has_key((ns_uri, "attr")) and \ attrs.keys() == [(ns_uri, "attr")] and \ attrs.get((ns_uri, "attr")) == "val" and \ attrs.get((ns_uri, "attr"), 25) == "val" and \ attrs.items() == [((ns_uri, "attr"), "val")] and \ attrs.values() == ["val"] and \ attrs.getValue((ns_uri, "attr")) == "val" and \ attrs.getValueByQName("ns:attr") == "val" and \ attrs.getNameByQName("ns:attr") == (ns_uri, "attr") and \ attrs[(ns_uri, "attr")] == "val" and \ attrs.getQNameByName((ns_uri, "attr")) == "ns:attr"