Example #1
0
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')
Example #2
0
    def write_home (self) :

        sects = {'ingredients' : 'Ingredients',
                 'directions' : 'Directions',
                 'stories' : 'Stories'}

        home_attrs = AttributesNSImpl({(NS_MAP['h'], 'id'):'home',
                                       (NS_MAP['h'], 'selected'):'true',
                                       (NS_MAP['h'], 'title'):'FIX ME'},
                                      {});

        self.xml.startElementNS((NS_MAP['h'], 'ul'), None, list_attrs)

        for id in sects :

            href = "#%s" % id
            
            home_attrs = AttributesNSImpl({(NS_MAP['h'], 'href'):href},
                                          {});

            self.xml.startElementNS((NS_MAP['h'], 'li'), None, {})
            self.xml.startElementNS((NS_MAP['h'], 'a'), None, link_attrs)            
            self.xml.characters(sects[id]);
            self.xml.endElementNS((NS_MAP['h'], 'a'), None)            
            self.xml.endElementNS((NS_MAP['h'], 'li'), None)
        
        self.xml.endElementNS((NS_MAP['h'], 'ul'), None)        
Example #3
0
def soql2atom(loginResult, soql, title):
    soqlWithFields = addRequiredFieldsToSoql(soql)
    userInfo = loginResult[beatbox._tPartnerNS.userInfo]
    serverUrl = str(loginResult[beatbox._tPartnerNS.serverUrl])
    (scheme, host, path, params, query, frag) = urlparse(serverUrl)
    sfbaseUrl = scheme + "://" + host + "/"
    thisUrl = "http://" + os.environ["HTTP_HOST"] + os.environ["REQUEST_URI"]
    qr = svc.query(soqlWithFields)

    atom_ns = "http://www.w3.org/2005/Atom"
    ent_ns = "urn:sobject.enterprise.soap.sforce.com"

    print("content-type: application/atom+xml")
    doGzip = "HTTP_ACCEPT_ENCODING" in os.environ and "gzip" in string.lower(os.environ["HTTP_ACCEPT_ENCODING"]).split(',')
    if doGzip:
        print("content-encoding: gzip")
    print("")
    x = beatbox.XmlWriter(doGzip)
    x.startPrefixMapping("a", atom_ns)
    x.startPrefixMapping("s", ent_ns)
    x.startElement(atom_ns, "feed")
    x.writeStringElement(atom_ns, "title", title)
    x.characters("\n")
    x.startElement(atom_ns, "author")
    x.writeStringElement(atom_ns, "name", str(userInfo.userFullName))
    x.endElement()
    x.characters("\n")
    rel = AttributesNSImpl(
        {(None, "rel"): "self", (None, "href"): thisUrl},
        {(None, "rel"): "rel",  (None, "href"): "href"})
    x.startElement(atom_ns, "link", rel)
    x.endElement()
    x.writeStringElement(atom_ns, "updated", datetime.datetime.utcnow().isoformat() + "Z")
    x.writeStringElement(atom_ns, "id", thisUrl + "&userid=" + str(loginResult[beatbox._tPartnerNS.userId]))
    x.characters("\n")
    type = AttributesNSImpl({(None, "type"): "html"}, {(None, "type"): "type"})
    for row in qr[sf.records:]:
        x.startElement(atom_ns, "entry")
        desc = ""
        x.writeStringElement(atom_ns, "title", str(row[2]))
        for col in row[2:]:
            if col._name[1] == 'Id':
                x.writeStringElement(atom_ns, "id", sfbaseUrl + str(col))
                writeLink(x, atom_ns, "link", "alternate", "text/html", sfbaseUrl + str(col))
            elif col._name[1] == 'SystemModstamp':
                x.writeStringElement(atom_ns, "updated", str(col))
            elif col._name[1] == 'CreatedDate':
                x.writeStringElement(atom_ns, "published", str(col))
            elif str(col) != "":
                desc = desc + "<b>" + col._name[1] + "</b> : " + str(col) + "<br>"
                x.writeStringElement(ent_ns, col._name[1], str(col))
        x.startElement(atom_ns, "content", type)
        x.characters(desc)
        x.endElement()  # content
        x.characters("\n")
        x.endElement()  # entry
    x.endElement()  # feed
    print(x.endDocument())
Example #4
0
def codebook_xml(tags, file):
    """Export a codebook in REFI-QDA format for the given tags.
    """
    with contextlib.ExitStack() as stack:
        if not hasattr(file, 'write'):
            file = stack.enter_context(open(file, 'wb'))

        # http://schema.qdasoftware.org/versions/Codebook/v1.0/Codebook.xsd
        output = XMLGenerator(
            file,
            encoding='utf-8',
            short_empty_elements=True,
        )
        output.startDocument()
        output.startPrefixMapping(None, 'urn:QDA-XML:codebook:1.0')
        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')
        output.endPrefixMapping(None)
        output.endDocument()
Example #5
0
    def write_instances(self, layer):
        attrs = AttributesNSImpl({}, {})
        self.startElement('instances', attrs)

        for inst in layer.getInstances():
            position = inst.getLocationRef().getExactLayerCoordinates()

            attr_vals = {
                (None, 'o'): inst.getObject().getId(),
                (None, 'x'): str(position.x),
                (None, 'y'): str(position.y),
                (None, 'z'): str(position.z),
                (None, 'r'): str(inst.getRotation()),
            }
            attr_names = {
                (None, 'o'): 'o',
                (None, 'x'): 'x',
                (None, 'y'): 'y',
                (None, 'z'): 'z',
                (None, 'r'): 'r',
            }

            visual = inst.get2dGfxVisual()
            if visual:
                attr_vals[(None, 'stackpos')] = str(visual.getStackPosition())
                attr_names[(None, 'stackpos')] = 'stackpos'

            nspace = inst.getObject().getNamespace()
            if nspace != self.nspace:
                attr_vals[(None, 'ns')] = inst.getObject().getNamespace()
                attr_names[(None, 'ns')] = 'ns'
                self.nspace = nspace

            instId = inst.getId()
            if instId:
                attr_vals[(None, 'id')] = inst.getId()
                attr_names[(None, 'id')] = 'id'

            if inst.isOverrideBlocking():
                attr_vals[(None, 'override_blocking')] = str(
                    int(inst.isOverrideBlocking()))
                attr_names[(None, 'override_blocking')] = 'override_blocking'
                if inst.getObject().isBlocking() is not inst.isBlocking():
                    attr_vals[(None, 'blocking')] = str(int(inst.isBlocking()))
                    attr_names[(None, 'blocking')] = 'blocking'

            attrs = AttributesNSImpl(attr_vals, attr_names)
            self.file.write(self.indent_level)
            self.xmlout.startElementNS((None, 'i'), 'i', attrs)
            self.xmlout.endElementNS((None, 'i'), 'i')
            self.file.write('\n')

        self.endElement('instances')
Example #6
0
 def elementUseStart(self, attrs, ns, name, qname):
     target = attrs.get(CardBackView.XLINK_HREF_ATTR)
     if not target:
         return False
     target = target.strip()
     if '#' == target[0] and self._id == target[1:] \
          and not self._outerSvgRendered:
         try:
             outerSvg = next(e for e in self._context
                             if (CardBackView.SVG_NAMESPACE,
                                 'svg') == e[:2])
         except StopIteration:
             self._error(None, 'Found <use> element outside of an <svg>')
         size = []
         for attr in CardBackView.ATTRS_SVG_DIMENSION:
             value, unit = self._distanceAttr(attrs, attr)
             if unit.strip():
                 self._error(
                     None, 'Attribute <use %s="%s" ...> is not valid'
                     ' in this context, expected a unit-free number.' %
                     (attr, attrs.get(None, attr)))
             if value is None:
                 self._error(
                     None, 'Attribute `%s` is missing from <use> element,'
                     ' but is expected in this context.' % attr)
             size.append(value)
         sattrs = ('%.6f%s' % (s * v, u)
                   for s, v, u in zip(self.scale, size, self.units))
         qnames = {
             name: outerSvg[3].getQNameByName(name)
             for name in outerSvg[3].getNames()
         }
         attrMap = dict(outerSvg[3].items())
         attrMap[(None, 'viewBox')] = self.boxValue((0, 0) + tuple(size))
         for attr in zip(CardBackView.ATTRS_SVG_DIMENSION, sattrs):
             attrMap[(None, attr[0])] = attr[1]
         self._sink.startElementNS(outerSvg[:2], outerSvg[2],
                                   AttributesNSImpl(attrMap, qnames))
         self._sink.ignorableWhitespace('\n')
         self._outerSvgRendered = True
         qnames = {
             name: attrs.getQNameByName(name)
             for name in attrs.getNames()
         }
         attrMap = dict(attrs.items())
         for attr in ('x', 'y') + CardBackView.ATTRS_SVG_DIMENSION:
             qnames.pop((None, attr), None)
             attrMap.pop((None, attr), None)
         self._sink.startElementNS((ns, name), qname,
                                   AttributesNSImpl(attrMap, qnames))
         self._sink.endElementNS((ns, name), qname)
         self._sink.ignorableWhitespace('\n')
     return False
Example #7
0
    def write_binding(self, name, val):
        assert self._resultStarted

        attr_vals = {
            (None, u"name"): str(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")
Example #8
0
 def write_header(self,allvarsL):
     self.writer.startElementNS((SPARQL_XML_NAMESPACE, u'head'), u'head', AttributesNSImpl({}, {}))
     for i in xrange(0,len(allvarsL)) :
         attr_vals = {
             (None, u'name'): unicode(allvarsL[i][1:]),
             }
         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')
Example #9
0
        def write_binding(self, name, val):
            assert self._resultStarted
            if val:
                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')
Example #10
0
def start_tag(doc, name, attr=None, body=None, namespace=None):
    """Wrapper to start an xml tag."""
    if attr is None:
        attr = {}


    # name = bytes(name, 'utf-8')
    
    # if namespace is not None:
        # namespace = bytes(namespace, 'utf-8')


    attr_vals = {}
    attr_keys = {}
    for key, val in attr.items():

            
        # if key is not None:
            # key = bytes(key, 'utf-8')
            
        # if val is not None:
            # val = bytes(val, 'utf-8')
        
        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)
Example #11
0
 def _element_ns(self, n):
     """ handle an ElementNode with NS interface"""
     ## convert DOM namedNodeMap to SAX attributes NS
     prefix_list = []
     nnm = n.attributes
     attrs, qnames = {}, {}
     for a in nnm.values():
         a_uri = a.namespaceURI
         if a_uri == XMLNS_NS:
             prefix, val = a.localName, a.value
             self._cont_handler.startPrefixMapping(prefix, val)
             prefix_list.append(prefix)
             if self._ns_prfx:
                 name = (a_uri, prefix)
                 attrs[name] = val
                 qnames[name] = a.nodeName
         else:
             name = (a_uri, a.localName)
             attrs[name] = a.value
             qnames[name] = a.nodeName
     ## handle element NS
     name = (n.namespaceURI, n.localName)
     self._cont_handler.startElementNS(name, n.nodeName,
                                       AttributesNSImpl(attrs, qnames))
     self._from_dom(n.firstChild)
     self._cont_handler.endElementNS(name, n.nodeName)
     prefix_list.reverse()
     map(self._cont_handler.endPrefixMapping, prefix_list)
Example #12
0
 def _defs(self, xml):
     element = self._svgName('defs')
     xml.ignorableWhitespace('\n ')
     xml.startElementNS(element, None, AttributesNSImpl({}, {}))
     self._edgePath(xml)
     xml.ignorableWhitespace('\n ')
     xml.endElementNS(element, None)
Example #13
0
    def write_source(self, source):
        self.xml.startElementNS((NS_MAP['e'], 'source'), None, {})

        if self.isset_notempty(source, 'publication'):

            xlink = {}

            if self.isset_notempty(source, 'identifier'):
                scheme, netloc, path, params, query, fragment = urlparse.urlparse(
                    source['identifier'])

                if not scheme == '':
                    xlink = AttributesNSImpl(
                        {(NS_MAP['xlink'], 'href'): source['identifier']}, {})

            self.xml.startElementNS((NS_MAP['e'], 'publication'), None, xlink)
            self.write_name(source['publication'])
            self.xml.endElementNS((NS_MAP['e'], 'publication'), None)

        if self.isset_notempty(source, 'author'):
            self.write_author(source['author'])

        if self.isset_notempty(source, 'date'):
            self.write_author(source['date'])

        self.xml.endElementNS((NS_MAP['e'], 'source'), None)
Example #14
0
 def write_ask(self, val):
     self.writer.startElementNS(
         (SPARQL_XML_NAMESPACE, u'boolean'),
          u'boolean', AttributesNSImpl({}, {}))
     self.writer.characters(str(val).lower())
     self.writer.endElementNS(
         (SPARQL_XML_NAMESPACE, u'boolean'), u'boolean')
Example #15
0
 def getAttrs(self, attrs={}):
     attr_values = {}
     attr_qnames = {}
     for key, value in attrs.iteritems():
         attr_values[(None, key)] = value
         attr_qnames[(None, key)] = key
     return AttributesNSImpl(attr_values, attr_qnames)
    def test_nest(self):
        """Testing deep nest"""
        file_object = StringIO()
        writer = XMLPrettyGenerator(file_object, 'UTF-8')
        writer.startDocument()
        attrs = AttributesNSImpl({}, {})
        writer.startElementNS((None, 'root'), 'root', attrs)
        writer.startElementNS((None, 'a'), 'a', attrs)
        writer.startElementNS((None, 'b'), 'b', attrs)
        writer.startElementNS((None, 'c'), 'c', attrs)
        writer.endElementNS((None, 'c'), 'c')
        writer.endElementNS((None, 'b'), 'b')
        writer.endElementNS((None, 'a'), 'a')
        writer.endElementNS((None, 'root'), 'root')
        writer.endDocument()
        result = file_object.getvalue()
        self.assertEqual(
            result.strip(), """
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <a>
        <b>
            <c></c>
        </b>
    </a>
</root>
""".strip())
Example #17
0
File: sax.py Project: xrile/fjord
def to_sax(walker, handler):
    """Call SAX-like content handler based on treewalker walker"""
    handler.startDocument()
    for prefix, namespace in prefix_mapping.items():
        handler.startPrefixMapping(prefix, namespace)

    for token in walker:
        type = token['type']
        if type == 'Doctype':
            continue
        elif type in ('StartTag', 'EmptyTag'):
            attrs = AttributesNSImpl(token['data'], unadjustForeignAttributes)
            handler.startElementNS((token['namespace'], token['name']),
                                   token['name'], attrs)
            if type == 'EmptyTag':
                handler.endElementNS((token['namespace'], token['name']),
                                     token['name'])
        elif type == 'EndTag':
            handler.endElementNS((token['namespace'], token['name']),
                                 token['name'])
        elif type in ('Characters', 'SpaceCharacters'):
            handler.characters(token['data'])
        elif type == 'Comment':
            pass
        else:
            assert False, 'Unknown token type'

    for prefix, namespace in prefix_mapping.items():
        handler.endPrefixMapping(prefix)
    handler.endDocument()
Example #18
0
def write_2(glos, filename):
    from xml.sax.saxutils import XMLGenerator
    from xml.sax.xmlreader import AttributesNSImpl
    xdbFp = open(filename, 'wb')
    fp = XMLGenerator(xdbFp, 'utf-8')
    attrs = AttributesNSImpl({}, {})
    fp.startElement(u'xfardic', attrs)
    for t in glos.info:
        fp.startElement(unicode(t[0]), attrs)
        fp.characters(unicode(t[1]))
        fp.endElement(unicode(t[0]))
    fp.endElement(u'xfardic')
    fp.startElement(u'words', attrs)
    for item in glos.data:
        try:
            tmpXmlFile.characters(item[1])
        except:
            log.exception('While writing xdb file, an error on word "%s":' %
                          item[0])
            continue
        fp.startElement(u'word', attrs)
        fp.startElement(u'in', attrs)
        fp.characters(unicode(item[0]))
        fp.endElement(u'in')
        fp.startElement(u'out', attrs)
        fp.characters(unicode(item[1]))
        fp.endElement(u'out')
    fp.endElement(u'words')
    fp.endDocument()
    xdbFp.close()
Example #19
0
def write_2(glos, filename):
    from xml.sax.saxutils import XMLGenerator
    from xml.sax.xmlreader import AttributesNSImpl
    xdbFp = open(filename, 'wb')
    fp = XMLGenerator(xdbFp, 'utf-8')
    attrs = AttributesNSImpl({}, {})
    fp.startElement('xfardic', attrs)
    for key, value in glos.iterInfo():
        fp.startElement(key, attrs)
        fp.characters(value)
        fp.endElement(key)
    fp.endElement('xfardic')
    fp.startElement('words', attrs)
    for entry in glos:
        word = entry.getWord()
        defi = entry.getDefi()
        try:
            tmpXmlFile.characters(defi)
        except:
            log.exception('While writing xdb file, an error on word "%s":' %
                          word)
            continue
        fp.startElement('word', attrs)
        fp.startElement('in', attrs)
        fp.characters(str(word))
        fp.endElement('in')
        fp.startElement('out', attrs)
        fp.characters(str(defi))
        fp.endElement('out')
    fp.endElement('words')
    fp.endDocument()
    xdbFp.close()
Example #20
0
def to_sax(walker, handler):
    """Call SAX-like content handler based on treewalker walker"""
    handler.startDocument()
    for prefix, namespace in list(prefix_mapping.items()):
        handler.startPrefixMapping(prefix, namespace)

    for token in walker:
        type = token["type"]
        if type == "Doctype":
            continue
        elif type in ("StartTag", "EmptyTag"):
            attrs = AttributesNSImpl(token["data"], unadjustForeignAttributes)
            handler.startElementNS((token["namespace"], token["name"]),
                                   token["name"], attrs)
            if type == "EmptyTag":
                handler.endElementNS((token["namespace"], token["name"]),
                                     token["name"])
        elif type == "EndTag":
            handler.endElementNS((token["namespace"], token["name"]),
                                 token["name"])
        elif type in ("Characters", "SpaceCharacters"):
            handler.characters(token["data"])
        elif type == "Comment":
            pass
        else:
            assert False, "Unknown token type"

    for prefix, namespace in list(prefix_mapping.items()):
        handler.endPrefixMapping(prefix)
    handler.endDocument()
 def start(self):
     """
     Start to writer out the XML.
     """
     self._writer.startDocument()
     attrs = AttributesNSImpl({}, {})
     self._writer.startElementNS((None, self._root), self._root, attrs)
    def write_entity(self, entity):
        """
        Write a entity out to the XML.
        """
        # default value for None
        type_default_values = {
            'int': -1,
            'decimal': -1.0,
            'string': '',
            'date': date.max.isoformat()
        }
        xmlattrs = AttributesNSImpl({}, {})
        self._writer.startElementNS((None, self._type_class), self._type_class, xmlattrs)
        field_list = entity.get_field_list()

        for field_name, stype, doc in field_list:
            self._writer.startElementNS((None, field_name), field_name, xmlattrs)
            # same as entity_attr = entity.`field_name`
            entity_attr = getattr(entity, field_name)
            attr_type = entity.typeof(field_name)
            if entity_attr == None:
                self._writer.characters(str(type_default_values[attr_type]))
            else:
                if attr_type == 'date':
                    # isoformat is YYYY-MM-DD.
                    self._writer.characters(entity_attr.isoformat())
                else:
                    self._writer.characters(str(entity_attr))
            self._writer.endElementNS((None, field_name), field_name)
        self._writer.endElementNS((None, self._type_class), self._type_class)
Example #23
0
    def edfg_attrs (self, attrs) :
        ns_attrs = {}
        qnames = {}
        
        for k, v in attrs.items() :
            ns_attrs[(NS_MAP['e'], k)] = v

        return AttributesNSImpl(ns_attrs, qnames);
Example #24
0
    def write_meta (self, name, content) :

        attrs = AttributesNSImpl({(NS_MAP['h'], 'name'):name,
                                  (NS_MAP['h'], 'content'):content},
                                  {});
        
        self.xml.startElementNS((NS_MAP['h'], 'meta'), None, attrs)
        self.xml.endElementNS((NS_MAP['e'], 'meta'), None)
Example #25
0
 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
Example #26
0
    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)
Example #27
0
    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)
Example #28
0
 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")
Example #29
0
    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)
Example #30
0
    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)