コード例 #1
0
 def _prettywrite(self, file, node, encoding, namespaces, depth=0):
     # write XML to file
     tag = node.tag
     if tag is Comment:
         file.write("\r\n" + "  " * depth)
         file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
     elif tag is ProcessingInstruction:
         file.write("\r\n" + "  " * depth)
         file.write("<?%s?>" % _escape_cdata(node.text, encoding))
     else:
         items = node.items()
         xmlns_items = [] # new namespaces in this scope
         try:
             if isinstance(tag, QName) or tag[:1] == "{":
                 tag, xmlns = myfixtag(tag, namespaces)
                 if xmlns:
                     xmlns_items.append(xmlns)
         except TypeError:
             _raise_serialization_error(tag)
         file.write("\r\n" + "  " * depth)
         file.write("<" + _encode(tag, encoding))
         if items or xmlns_items:
             items.sort() # lexical order
             for k, v in items:
                 try:
                     if isinstance(k, QName) or k[:1] == "{":
                         k, xmlns = myfixtag(k, namespaces)
                         if xmlns:
                             xmlns_items.append(xmlns)
                 except TypeError:
                     _raise_serialization_error(k)
                 try:
                     if isinstance(v, QName):
                         v, xmlns = myfixtag(v, namespaces)
                         if xmlns:
                             xmlns_items.append(xmlns)
                 except TypeError:
                     _raise_serialization_error(v)
                 file.write(" %s=\"%s\"" % (_encode(k, encoding),
                                            _escape_attrib(v, encoding)))
             for k, v in xmlns_items:
                 file.write(" %s=\"%s\"" % (_encode(k, encoding),
                                            _escape_attrib(v, encoding)))
         if node.text or len(node):
             file.write(">")
             if node.text:
                 file.write(_escape_cdata(node.text, encoding))
             for n in node:
                 self._prettywrite(file, n, encoding, namespaces, depth=depth + 1)
             if not node.text or len(node):
                 file.write("\r\n" + "  " * depth)
             file.write("</" + _encode(tag, encoding) + ">")
         else:
             file.write(" />")
         for k, v in xmlns_items:
             del namespaces[v]
     if node.tail:
         file.write(_escape_cdata(node.tail, encoding))
コード例 #2
0
ファイル: merge_xml.py プロジェクト: UFOslava/se-blender
def _serialize_xml(write, elem, qnames, namespaces, short_empty_elements,
                   **kwargs):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % text)
    elif tag is ProcessingInstruction:
        write("<?%s?>" % text)
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text))
            for e in elem:
                _serialize_xml(write,
                               e,
                               qnames,
                               None,
                               short_empty_elements=short_empty_elements)
        else:
            write("<" + tag)
            items = list(elem.items())
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (k, _escape_attrib(v)))

                # below is the changed line. assuming attrib is an OrderedDict this will preserve attribute order
                for k, v in elem.attrib.items():
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(v)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem) or not short_empty_elements:
                write(">")
                if text:
                    write(_escape_cdata(text))
                for e in elem:
                    _serialize_xml(write,
                                   e,
                                   qnames,
                                   None,
                                   short_empty_elements=short_empty_elements)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(_escape_cdata(elem.tail))
コード例 #3
0
ファイル: exporter.py プロジェクト: p2pu/osqa-badges
def Etree_pretty__write(self, file, node, encoding, namespaces,
                        level=0, identator="    "):
    tag = node.tag
    if tag is Comment:
        file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
    elif tag is ProcessingInstruction:
        file.write("<?%s?>" % _escape_cdata(node.text, encoding))
    else:
        items = node.items()
        xmlns_items = [] # new namespaces in this scope
        try:
            if isinstance(tag, QName) or tag[:1] == "{":
                tag, xmlns = fixtag(tag, namespaces)
                if xmlns: xmlns_items.append(xmlns)
        except TypeError:
            raise #_raise_serialization_error(tag)
        file.write("\n" + level * identator + "<" + _encode(tag, encoding))
        if items or xmlns_items:
            items.sort() # lexical order
            for k, v in items:
                try:
                    if isinstance(k, QName) or k[:1] == "{":
                        k, xmlns = fixtag(k, namespaces)
                        if xmlns: xmlns_items.append(xmlns)
                except TypeError:
                    raise #_raise_serialization_error(k)
                try:
                    if isinstance(v, QName):
                        v, xmlns = fixtag(v, namespaces)
                        if xmlns: xmlns_items.append(xmlns)
                except TypeError:
                    raise #_raise_serialization_error(v)
                file.write(u" %s=\"%s\"" % (_encode(k, encoding),
                                            _escape_attrib(v, encoding)))
            for k, v in xmlns_items:
                file.write(u" %s=\"%s\"" % (_encode(k, encoding),
                                            _escape_attrib(v, encoding)))
        if node.text or len(node):
            file.write(">")
            if node.text:
                file.write(_escape_cdata(node.text.replace("\n", (level + 1) * identator + "\n"), encoding))
            for n in node:
                self._write(file, n, encoding, namespaces, level + 1, identator)
            if node.text and len(node.text) < 125:
                file.write("</" + _encode(tag, encoding) + ">")
            else:
                file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
        else:
            file.write(" />")
        for k, v in xmlns_items:
            del namespaces[v]
    if node.tail:
        file.write(_escape_cdata(node.tail.replace("\n", level * identator + "\n"), encoding))
コード例 #4
0
ファイル: exporter.py プロジェクト: m10n/bestofever
def Etree_pretty__write(self, file, node, encoding, namespaces,
                        level=0, identator="    "):
    tag = node.tag
    if tag is Comment:
        file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
    elif tag is ProcessingInstruction:
        file.write("<?%s?>" % _escape_cdata(node.text, encoding))
    else:
        items = node.items()
        xmlns_items = [] # new namespaces in this scope
        try:
            if isinstance(tag, QName) or tag[:1] == "{":
                tag, xmlns = fixtag(tag, namespaces)
                if xmlns: xmlns_items.append(xmlns)
        except TypeError:
            raise #_raise_serialization_error(tag)
        file.write("\n" + level * identator + "<" + _encode(tag, encoding))
        if items or xmlns_items:
            items.sort() # lexical order
            for k, v in items:
                try:
                    if isinstance(k, QName) or k[:1] == "{":
                        k, xmlns = fixtag(k, namespaces)
                        if xmlns: xmlns_items.append(xmlns)
                except TypeError:
                    raise #_raise_serialization_error(k)
                try:
                    if isinstance(v, QName):
                        v, xmlns = fixtag(v, namespaces)
                        if xmlns: xmlns_items.append(xmlns)
                except TypeError:
                    raise #_raise_serialization_error(v)
                file.write(u" %s=\"%s\"" % (_encode(k, encoding),
                                            _escape_attrib(v, encoding)))
            for k, v in xmlns_items:
                file.write(u" %s=\"%s\"" % (_encode(k, encoding),
                                            _escape_attrib(v, encoding)))
        if node.text or len(node):
            file.write(">")
            if node.text:
                file.write(_escape_cdata(node.text, encoding))
            for n in node:
                self._write(file, n, encoding, namespaces, level + 1, identator)
            if node.text and len(node.text) < 125:
                file.write("</" + _encode(tag, encoding) + ">")
            else:
                file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
        else:
            file.write(" />")
        for k, v in xmlns_items:
            del namespaces[v]
    if node.tail:
        file.write(_escape_cdata(node.tail.replace("\n", (level * identator )+ "\n"), encoding))
コード例 #5
0
ファイル: utils.py プロジェクト: pombredanne/opentrackings
    def _print_node(self, node, encoding):
        tree_string = ""

        tag = node.tag
        if tag is Comment:
            tree_string += "<!-- %s -->" % _escape_cdata(node.text, encoding)
        elif tag is ProcessingInstruction:
            tree_string += "<?%s?>" % _escape_cdata(node.text, encoding)
        else:
            items = node.items()
            xmlns_items = [] # new namespaces in this scope
            try:
                if isinstance(tag, QName) or tag[:1] == "{":
                    tag, xmlns = fixtag(tag, namespaces)
                    if xmlns: xmlns_items.append(xmlns)
            except TypeError:
                _raise_serialization_error(tag)
            tree_string += "<" + _encode(tag, encoding)
            if items or xmlns_items:
                items.sort() # lexical order
                for k, v in items:
                    try:
                        if isinstance(k, QName) or k[:1] == "{":
                            k, xmlns = fixtag(k, namespaces)
                            if xmlns: xmlns_items.append(xmlns)
                    except TypeError:
                        _raise_serialization_error(k)
                    try:
                        if isinstance(v, QName):
                            v, xmlns = fixtag(v, namespaces)
                            if xmlns: xmlns_items.append(xmlns)
                    except TypeError:
                        _raise_serialization_error(v)
                    tree_string += " %s=\"%s\"" % (_encode(k, encoding),
                                               _escape_attrib(v, encoding))
                for k, v in xmlns_items:
                    tree_string += " %s=\"%s\"" % (_encode(k, encoding),
                                               _escape_attrib(v, encoding))

            tree_string += ">"
            if node.text:
                tree_string += _escape_cdata(node.text, encoding).replace('"', '&quot;')
            for n in node:
                tree_string += self._print_node(n, encoding)
            tree_string += "</" + _encode(tag, encoding) + ">"
            for k, v in xmlns_items:
                del namespaces[v]

        if node.tail:
            tree_string += _escape_cdata(node.tail, encoding)

        return tree_string
コード例 #6
0
ファイル: merge_xml.py プロジェクト: CyberSys/se-blender
def _serialize_xml(write, elem, qnames, namespaces,
                   short_empty_elements, **kwargs):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % text)
    elif tag is ProcessingInstruction:
        write("<?%s?>" % text)
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text))
            for e in elem:
                _serialize_xml(write, e, qnames, None,
                               short_empty_elements=short_empty_elements)
        else:
            write("<" + tag)
            items = list(elem.items())
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (
                            k,
                            _escape_attrib(v)
                            ))

                # below is the changed line. assuming attrib is an OrderedDict this will preserve attribute order
                for k, v in elem.attrib.items():
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(v)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem) or not short_empty_elements:
                write(">")
                if text:
                    write(_escape_cdata(text))
                for e in elem:
                    _serialize_xml(write, e, qnames, None,
                                   short_empty_elements=short_empty_elements)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(_escape_cdata(elem.tail))
コード例 #7
0
def _serialize_xml(write, elem, qnames, namespaces, short_empty_elements,
                   **kwargs):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write("<!--%s-->" % text)
    elif tag is ProcessingInstruction:
        write("<?%s?>" % text)
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text))
            for e in elem:
                _serialize_xml(write,
                               e,
                               qnames,
                               None,
                               short_empty_elements=short_empty_elements)
        else:
            write("<" + tag)
            items = list(elem.items())
            if items or namespaces:
                if namespaces:
                    for v, k in namespaces.items():  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (k, _escape_attrib(str(v))))
                for k, v in items:  # lexical order
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(str(v))
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem) or not short_empty_elements:
                write(">")
                if text:
                    write(_escape_cdata(text))
                for e in elem:
                    _serialize_xml(write,
                                   e,
                                   qnames,
                                   None,
                                   short_empty_elements=short_empty_elements)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(_escape_cdata(elem.tail))
コード例 #8
0
ファイル: service.py プロジェクト: DMRobertson/scscpy
def instruction(*args):
	"""Forms an XML processing instruction (as a string) from the arguments. If there is an odd number of arguments, the first is taken to be a key. The rest are attribute/value pairs, in order. If an even number of arguments is given, they are all treated as attribute/value pairs."""
	if len(args) % 2 == 1:
		details = args[0] + " "
		start = 1
	else:
		details = ""
		start = 0
	for i in range(start, len(args), 2):
		attrib, value = args[i], args[i+1]
		details += "{}=\"{}\" ".format(attrib, _escape_attrib(str(value)))
	return "<?scscp " + details + "?>\n"
コード例 #9
0
ファイル: service.py プロジェクト: DMRobertson/scscpy
def instruction(*args):
    """Forms an XML processing instruction (as a string) from the arguments. If there is an odd number of arguments, the first is taken to be a key. The rest are attribute/value pairs, in order. If an even number of arguments is given, they are all treated as attribute/value pairs."""
    if len(args) % 2 == 1:
        details = args[0] + " "
        start = 1
    else:
        details = ""
        start = 0
    for i in range(start, len(args), 2):
        attrib, value = args[i], args[i + 1]
        details += "{}=\"{}\" ".format(attrib, _escape_attrib(str(value)))
    return "<?scscp " + details + "?>\n"
コード例 #10
0
    def _write(self, file, node, encoding, namespaces, sortflag="default", sortcmp=None): # don't break existing code that relies on _write()s parameters, if any
        # write XML to file
        tag = node.tag
        if tag is Comment:
            file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
        elif tag is ProcessingInstruction:
            file.write("<?%s?>" % _escape_cdata(node.text, encoding))
        else:
            items = node.items()
            xmlns_items = [] # new namespaces in this scope
            try:
                if isinstance(tag, QName) or tag[:1] == "{":
                    tag, xmlns = fixtag(tag, namespaces)
                    if xmlns: xmlns_items.append(xmlns)
            except TypeError:
                _raise_serialization_error(tag)
            file.write("<" + _encode(tag, encoding))
            if items or xmlns_items:
                
                ##NEW

                if sortflag!="default":
                    if ":" not in sortflag:
                        sortflag = ":"+sortflag
                    sortitems = sortflag.split(";")
                    try:
                        sortitems = [[tagdef.split(":")[0], tagdef.split(":")[1].split(",")] for tagdef in sortitems]
                        temp = []
                        for tagdef in sortitems:
                            if tagdef[0] in node.tag:
                                for sortitem in tagdef[1]:
                                    temp.extend([i for i in items if sortitem in i]) # add what matches pattern
                                break
                        # then sort and add what's left
                        items.sort(cmp=sortcmp)
                        temp.extend([i for i in items if i not in temp])
                        items = temp
                    except IndexError:
                        sys.stderr.write("sortflag not formatted correctly, order won't be applied")
                        try:
                            items.sort(cmp=sortcmp)
                        except:
                            sys.stderr.write("sortcmp not a valid comparator, sorting alphabetically instead")
                            items.sort()
                else:
                    try:
                        items.sort(cmp=sortcmp)
                    except:
                        sys.stderr.write("sortcmp not a valid comparator, sorting alphabetically instead")
                        items.sort()
                ###

                        
                for k, v in items:
                    try:
                        if isinstance(k, QName) or k[:1] == "{":
                            k, xmlns = fixtag(k, namespaces)
                            if xmlns: xmlns_items.append(xmlns)
                    except TypeError:
                        _raise_serialization_error(k)
                    try:
                        if isinstance(v, QName):
                            v, xmlns = fixtag(v, namespaces)
                            if xmlns: xmlns_items.append(xmlns)
                    except TypeError:
                        _raise_serialization_error(v)
                    file.write(" %s=\"%s\"" % (_encode(k, encoding),
                                               _escape_attrib(v, encoding)))
                for k, v in xmlns_items:
                    file.write(" %s=\"%s\"" % (_encode(k, encoding),
                                               _escape_attrib(v, encoding)))
            if node.text or len(node):
                file.write(">")
                if node.text:
                    file.write(_escape_cdata(node.text, encoding))
                for n in node:
                    self._write(file, n, encoding, namespaces, sortflag, sortcmp)
                file.write("</" + _encode(tag, encoding) + ">")
            else:
                file.write(" />")
            for k, v in xmlns_items:
                del namespaces[v]
        if node.tail:
            file.write(_escape_cdata(node.tail, encoding))
コード例 #11
0
def _serialize_xml(write,
                   elem,
                   qnames,
                   namespaces,
                   short_empty_elements,
                   addintend="    ",
                   intend="",
                   newl="\n",
                   **kwargs):
    tag = elem.tag
    text = elem.text
    if tag is Comment:
        write(intend + "<!--%s-->" % text)
    elif tag is ProcessingInstruction:
        write(intend + "<?%s?>" % text)
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text))
            for e in elem:
                _serialize_xml(write,
                               e,
                               qnames,
                               None,
                               addintend=addintend,
                               intend=addintend + intend,
                               newl=newl,
                               short_empty_elements=short_empty_elements)
        else:
            write(intend + "<" + tag)
            items = list(elem.items())
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (k, _escape_attrib(v)))
                for k, v in sorted(items):  # lexical order
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(v)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem) or not short_empty_elements:
                write(">")
                if text is not None:
                    write(_escape_cdata(text))
                else:
                    if len(elem.getchildren()) > 0:
                        write(newl)
                for e in elem:
                    _serialize_xml(write,
                                   e,
                                   qnames,
                                   None,
                                   addintend=addintend,
                                   intend=addintend + intend,
                                   newl=newl,
                                   short_empty_elements=short_empty_elements)
                if len(elem.getchildren()) > 0:
                    write(intend)
                write("</" + tag + ">" + newl)
            else:
                write(" />" + newl)
    if elem.tail:
        write(_escape_cdata(elem.tail))
コード例 #12
0
 def _prettywrite(self, file, node, encoding, namespaces, depth=0):
     # write XML to file
     tag = node.tag
     if tag is Comment:
         file.write("\r\n" + "  " * depth)
         file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
     elif tag is ProcessingInstruction:
         file.write("\r\n" + "  " * depth)
         file.write("<?%s?>" % _escape_cdata(node.text, encoding))
     else:
         items = node.items()
         xmlns_items = []  # new namespaces in this scope
         try:
             if isinstance(tag, QName) or tag[:1] == "{":
                 tag, xmlns = myfixtag(tag, namespaces)
                 if xmlns:
                     xmlns_items.append(xmlns)
         except TypeError:
             _raise_serialization_error(tag)
         file.write("\r\n" + "  " * depth)
         file.write("<" + _encode(tag, encoding))
         if items or xmlns_items:
             items.sort()  # lexical order
             for k, v in items:
                 try:
                     if isinstance(k, QName) or k[:1] == "{":
                         k, xmlns = myfixtag(k, namespaces)
                         if xmlns:
                             xmlns_items.append(xmlns)
                 except TypeError:
                     _raise_serialization_error(k)
                 try:
                     if isinstance(v, QName):
                         v, xmlns = myfixtag(v, namespaces)
                         if xmlns:
                             xmlns_items.append(xmlns)
                 except TypeError:
                     _raise_serialization_error(v)
                 file.write(
                     " %s=\"%s\"" %
                     (_encode(k, encoding), _escape_attrib(v, encoding)))
             for k, v in xmlns_items:
                 file.write(
                     " %s=\"%s\"" %
                     (_encode(k, encoding), _escape_attrib(v, encoding)))
         if node.text or len(node):
             file.write(">")
             if node.text:
                 file.write(_escape_cdata(node.text, encoding))
             for n in node:
                 self._prettywrite(file,
                                   n,
                                   encoding,
                                   namespaces,
                                   depth=depth + 1)
             if not node.text or len(node):
                 file.write("\r\n" + "  " * depth)
             file.write("</" + _encode(tag, encoding) + ">")
         else:
             file.write(" />")
         for k, v in xmlns_items:
             del namespaces[v]
     if node.tail:
         file.write(_escape_cdata(node.tail, encoding))