Esempio n. 1
0
 def __init__(self, xml_out=None, basedir=None):
     """
     @param xml_out: Output filename, if None, will dump to tempfile
     @param basedir: working directory, where file will be created
     """
     if xml_out:
         self.filename = xml_out
         fd = open(xml_out, 'w')
     else:
         try:
             (fdesc, self.filename) = tempfile.mkstemp('.xml', 'pyx12_')
             fd = os.fdopen(fdesc, 'w+b')
             #fd = tempfile.NamedTemporaryFile()
             #self.filename = fd.name
         except:
             #self.filename = '997.tmp.xml'
             (fdesc, self.filename) = tempfile.mkstemp(suffix='.xml',
                                                       prefix='pyx12_',
                                                       dir=basedir)
             fd = os.fdopen(fdesc, 'w+b')
             #fd = file(os.path.join(basedir, self.filename), 'w')
     self.cur_line = None
     self.errors = []
     if not fd:
         raise EngineError('Could not open temp error xml file')
     self.writer = XMLWriter(fd)
     #self.writer.doctype(
     #    u"x12simple", u"-//J Holland//DTD XML X12 Document
     #    Conversion1.0//EN//XML",
     #    u"%s" % (dtd_urn))
     self.writer.push("x12err")
Esempio n. 2
0
 def test_init(self):
     """Testing __init__"""
     file_object = StringIO()
     for class_name in entity.keys():
         reader = XMLWriter(file_object, class_name)
     with self.assertRaises(DataWriterException):
         reader = XMLWriter(file_object, 'Foo')
Esempio n. 3
0
 def __init__(self, fd, type, dtd_urn):
     self.writer = XMLWriter(fd)
     if dtd_urn:
         self.writer.doctype(
             type,
             "-//J Holland//DTD XML X12 Document Conversion1.0//EN//XML",
             "%s" % (dtd_urn))
     self.writer.push(type)
     self.last_path = None
Esempio n. 4
0
 def writeXML(self):
     try:
         print "trying to write..."
         xml = XMLWriter(self.objects, "borgball",
                         (str(self.imIdx) + ".jpg"), 240, 320, 3,
                         (self.exportfolder + str(self.imIdx) + ".xml"))
         xml.write()
     except Exception as ex:
         print ex
         print "something went wrong during writeXML()"
Esempio n. 5
0
 def save_click(self):
     filename = QtGui.QFileDialog.getSaveFileName(self,
                     "Select a file for parameters",
                     "supervisors",
                     "XML files (*.xml)")
     if filename is not None:
         writer = XMLWriter(filename, 'parameters', self.contents.get_xmlstruct())
         try:
             writer.write()
         except Exception as e:
             QtGui.QMessageBox.critical(self,"Saving parameters failed",str(e))
 def save_click(self):
     filename = QtGui.QFileDialog.getSaveFileName(self,
                     "Select a file for parameters",
                     "supervisors",
                     "XML files (*.xml)")
     if filename is not None:
         writer = XMLWriter(filename, 'parameters', self.contents.get_xmlstruct())
         try:
             writer.write()
         except Exception as e:
             #QtGui.QMessageBox.critical(self,"Saving parameters failed",str(e))
             QtGui.QMessageBox.critical(self,"Saving parameters failed","\n".join(format_exception(*sys.exc_info())))
Esempio n. 7
0
 def __init__(self, xml_out=None, basedir=None):
     """
     @param xml_out: Output filename, if None, will dump to tempfile
     @param basedir: working directory, where file will be created
     """
     if xml_out:
         self.filename = xml_out
         fd = open(xml_out, 'w')
     else:
         try:
             (fdesc, self.filename) = tempfile.mkstemp('.xml', 'pyx12_')
             fd = os.fdopen(fdesc, 'w+b')
             #fd = tempfile.NamedTemporaryFile()
             #self.filename = fd.name
         except:
             #self.filename = '997.tmp.xml'
             (fdesc, self.filename) = tempfile.mkstemp(suffix='.xml',
                                                       prefix='pyx12_', dir=basedir)
             fd = os.fdopen(fdesc, 'w+b')
             #fd = file(os.path.join(basedir, self.filename), 'w')
     self.cur_line = None
     self.errors = []
     if not fd:
         raise EngineError('Could not open temp error xml file')
     self.writer = XMLWriter(fd)
     #self.writer.doctype(
     #    u"x12simple", u"-//J Holland//DTD XML X12 Document
     #    Conversion1.0//EN//XML",
     #    u"%s" % (dtd_urn))
     self.writer.push("x12err")
Esempio n. 8
0
 def __init__(self, fd, type, dtd_urn):
     self.writer = XMLWriter(fd)
     if dtd_urn:
         self.writer.doctype(
             type, "-//J Holland//DTD XML X12 Document Conversion1.0//EN//XML",
             "%s" % (dtd_urn))
     self.writer.push(type)
     self.last_path = None
Esempio n. 9
0
    def test_dump(self):
        """Testing dumping two instance"""
        file_object = StringIO()
        writer = XMLWriter(file_object, 'Testing')
        writer.start()

        instance = Testing()
        instance.f1 = 'aaa'
        import datetime
        instance.f2 = datetime.datetime(1999, 2, 3).date()
        instance.f3 = 1
        instance.f4 = 1
        writer.write_entity(instance)

        instance.f1 = 'bbb'
        import datetime
        instance.f2 = datetime.datetime(2009, 2, 3).date()
        instance.f3 = 2
        instance.f4 = 2
        writer.write_entity(instance)

        writer.end()
        result = file_object.getvalue()
        self.assertEqual(
            result.strip(), """
<?xml version="1.0" encoding="UTF-8"?>
<Testings>
    <Testing>
        <f1>aaa</f1>
        <f2>1999-02-03</f2>
        <f3>1</f3>
        <f4>1.0</f4>
    </Testing>
    <Testing>
        <f1>bbb</f1>
        <f2>2009-02-03</f2>
        <f3>2</f3>
        <f4>2.0</f4>
    </Testing>
</Testings>
""".strip())
Esempio n. 10
0
    def test_write_parameters_bad_parameter_float_key(self):
        parameters = {'pid': {
                             'goal': {'13.0': '10.0', 'x': 11.0}, 
                             'angle': {'theta': 0.7854}, 
                             'velocity': {'v': 0.1}, 
                             ('gains', 'soft'): {'ki': 0.1, 'kp': 5.0, 'kd': 0.01}, 
                             ('gains', 'hard'): {'ki': 0.1, 'kp': 5.0, 'kd': 0.01}
                             }
                     }

        writer = XMLWriter("bad_parameter.xml", "parameters", parameters)
        self.assertRaises(Exception, writer.write)
    def test_dump(self):
        """Testing dumping two instance"""
        file_object = StringIO()
        writer = XMLWriter(file_object, 'Testing')
        writer.start()

        instance = Testing()
        instance.f1 = 'aaa'
        import datetime
        instance.f2 = datetime.datetime(1999, 2, 3).date()
        instance.f3 = 1
        instance.f4 = 1
        writer.write_entity(instance)

        instance.f1 = 'bbb'
        import datetime
        instance.f2 = datetime.datetime(2009, 2, 3).date()
        instance.f3 = 2
        instance.f4 = 2
        writer.write_entity(instance)

        writer.end()
        result = file_object.getvalue()
        self.assertEqual(result.strip(),
"""
<?xml version="1.0" encoding="UTF-8"?>
<Testings>
    <Testing>
        <f1>aaa</f1>
        <f2>1999-02-03</f2>
        <f3>1</f3>
        <f4>1.0</f4>
    </Testing>
    <Testing>
        <f1>bbb</f1>
        <f2>2009-02-03</f2>
        <f3>2</f3>
        <f4>2.0</f4>
    </Testing>
</Testings>
""".strip())
Esempio n. 12
0
    def test_default_value(self):
        """Testing default value"""
        file_object = StringIO()
        writer = XMLWriter(file_object, 'Testing')
        instance = Testing()
        writer.start()
        writer.write_entity(instance)
        writer.end()
        result = file_object.getvalue()
        self.assertEqual(
            result.strip(), """
<?xml version="1.0" encoding="UTF-8"?>
<Testings>
    <Testing>
        <f1></f1>
        <f2>9999-12-31</f2>
        <f3>-1</f3>
        <f4>-1.0</f4>
    </Testing>
</Testings>""".strip())
    def test_default_value(self):
        """Testing default value"""
        file_object = StringIO()
        writer = XMLWriter(file_object, 'Testing')
        instance = Testing()
        writer.start()
        writer.write_entity(instance)
        writer.end()
        result = file_object.getvalue()
        self.assertEqual(result.strip(),
                         """
<?xml version="1.0" encoding="UTF-8"?>
<Testings>
    <Testing>
        <f1></f1>
        <f2>9999-12-31</f2>
        <f3>-1</f3>
        <f4>-1.0</f4>
    </Testing>
</Testings>""".strip())
Esempio n. 14
0
    def test_write_parameters_legal(self):
        parameters = {'pid': {
                             'goal': {'y': 10.0, 'x': 11.0}, 
                             'angle': {'theta': 0.7854}, 
                             'velocity': {'v': 0.1}, 
                             ('gains', 'soft'): {'ki': 0.1, 'kp': 5.0, 'kd': 0.01}, 
                             ('gains', 'hard'): {'ki': 0.1, 'kp': 5.0, 'kd': 0.01}
                             }
                     }

        file_ = "tmp_removeme.xml"
        try:
            XMLWriter(file_, "parameters", parameters).write()
            result = XMLReader(file_, "parameters").read()
            assert result == parameters
        finally:
            # If the file was created (it exists), delete it
            try:
                with open(file_) as f:
                    f.close()
                    unlink(file_)
            except IOError:
                pass
Esempio n. 15
0
class err_handler(object):
    """
    The interface to the error handling structures.
    """
    def __init__(self, xml_out=None, basedir=None):
        """
        @param xml_out: Output filename, if None, will dump to tempfile
        @param basedir: working directory, where file will be created
        """
        if xml_out:
            self.filename = xml_out
            fd = open(xml_out, 'w')
        else:
            try:
                (fdesc, self.filename) = tempfile.mkstemp('.xml', 'pyx12_')
                fd = os.fdopen(fdesc, 'w+b')
                #fd = tempfile.NamedTemporaryFile()
                #self.filename = fd.name
            except:
                #self.filename = '997.tmp.xml'
                (fdesc, self.filename) = tempfile.mkstemp(suffix='.xml',
                                                          prefix='pyx12_', dir=basedir)
                fd = os.fdopen(fdesc, 'w+b')
                #fd = file(os.path.join(basedir, self.filename), 'w')
        self.cur_line = None
        self.errors = []
        if not fd:
            raise EngineError('Could not open temp error xml file')
        self.writer = XMLWriter(fd)
        #self.writer.doctype(
        #    u"x12simple", u"-//J Holland//DTD XML X12 Document
        #    Conversion1.0//EN//XML",
        #    u"%s" % (dtd_urn))
        self.writer.push("x12err")

    def __del__(self):
        while len(self.writer) > 0:
            self.writer.pop()

    def getFilename(self):
        return self.filename

    def handleErrors(self, err_list):
        """
        @param err_list: list of errors to apply
        """
        self.errors.extend(err_list)
        #for (err_type, err_cde, err_str, err_val, src_line) in err_list:
        #    if err_type == 'isa':
        #        self.isa_error(err_cde, err_str)
        #    elif err_type == 'gs':
        #        self.gs_error(err_cde, err_str)
        #    elif err_type == 'st':
        #        self.st_error(err_cde, err_str)
        #    elif err_type == 'seg':
        #        self.seg_error(err_cde, err_str, err_val, src_line)

    def getCurLine(self):
        """
        @return: Current file line number
        @rtype: int
        """
        return self.cur_line

    def Write(self, cur_line):
        """
        Generate XML for the segment data and matching map node

        """
        if len(self.errors) > 0:
            self.writer.push("seg", attrs={'line': '%i' % (cur_line)})
            for (err_type, err_cde, err_str, err_val, src_line) in self.errors:
                self.writer.push("err", attrs={"code": err_cde})
                #self.writer.elem(u"type", err_type)
                #self.writer.elem(u"code", err_cde)
                self.writer.elem("desc", err_str)
                if err_val:
                    self.writer.elem("errval", err_val)
                #self.writer.push(u"seg", {u'line': '%i'%(cur_line)})
                        #self.writer.elem(u'ele', seg_data.get_value('%02i' %
                        #(i+1)),
                        #    attrs={u'id': child_node.id})
                self.writer.pop()  # end err
            self.writer.pop()  # end segment
            self.errors = []
Esempio n. 16
0
class err_handler(object):
    """
    The interface to the error handling structures.
    """
    def __init__(self, xml_out=None, basedir=None):
        """
        @param xml_out: Output filename, if None, will dump to tempfile
        @param basedir: working directory, where file will be created
        """
        if xml_out:
            self.filename = xml_out
            fd = open(xml_out, 'w')
        else:
            try:
                (fdesc, self.filename) = tempfile.mkstemp('.xml', 'pyx12_')
                fd = os.fdopen(fdesc, 'w+b')
                #fd = tempfile.NamedTemporaryFile()
                #self.filename = fd.name
            except:
                #self.filename = '997.tmp.xml'
                (fdesc, self.filename) = tempfile.mkstemp(suffix='.xml',
                                                          prefix='pyx12_',
                                                          dir=basedir)
                fd = os.fdopen(fdesc, 'w+b')
                #fd = file(os.path.join(basedir, self.filename), 'w')
        self.cur_line = None
        self.errors = []
        if not fd:
            raise EngineError('Could not open temp error xml file')
        self.writer = XMLWriter(fd)
        #self.writer.doctype(
        #    u"x12simple", u"-//J Holland//DTD XML X12 Document
        #    Conversion1.0//EN//XML",
        #    u"%s" % (dtd_urn))
        self.writer.push("x12err")

    def __del__(self):
        while len(self.writer) > 0:
            self.writer.pop()

    def getFilename(self):
        return self.filename

    def handleErrors(self, err_list):
        """
        @param err_list: list of errors to apply
        """
        self.errors.extend(err_list)
        #for (err_type, err_cde, err_str, err_val, src_line) in err_list:
        #    if err_type == 'isa':
        #        self.isa_error(err_cde, err_str)
        #    elif err_type == 'gs':
        #        self.gs_error(err_cde, err_str)
        #    elif err_type == 'st':
        #        self.st_error(err_cde, err_str)
        #    elif err_type == 'seg':
        #        self.seg_error(err_cde, err_str, err_val, src_line)

    def getCurLine(self):
        """
        @return: Current file line number
        @rtype: int
        """
        return self.cur_line

    def Write(self, cur_line):
        """
        Generate XML for the segment data and matching map node

        """
        if len(self.errors) > 0:
            self.writer.push("seg", attrs={'line': '%i' % (cur_line)})
            for (err_type, err_cde, err_str, err_val, src_line) in self.errors:
                self.writer.push("err", attrs={"code": err_cde})
                #self.writer.elem(u"type", err_type)
                #self.writer.elem(u"code", err_cde)
                self.writer.elem("desc", err_str)
                if err_val:
                    self.writer.elem("errval", err_val)
                #self.writer.push(u"seg", {u'line': '%i'%(cur_line)})
                #self.writer.elem(u'ele', seg_data.get_value('%02i' %
                #(i+1)),
                #    attrs={u'id': child_node.id})
                self.writer.pop()  # end err
            self.writer.pop()  # end segment
            self.errors = []
Esempio n. 17
0
class x12xml(object):
    def __init__(self, fd, type, dtd_urn):
        self.writer = XMLWriter(fd)
        if dtd_urn:
            self.writer.doctype(
                type,
                "-//J Holland//DTD XML X12 Document Conversion1.0//EN//XML",
                "%s" % (dtd_urn))
        self.writer.push(type)
        self.last_path = None

    def __del__(self):
        pass

    def seg(self, seg_node, seg_data):
        """
        Generate XML for the segment data and matching map node

        @param seg_node: Map Node
        @type seg_node: L{node<map_if.x12_node>}
        @param seg_data: Segment object
        @type seg_data: L{segment<segment.Segment>}
        """
        if not seg_node.is_segment():
            raise EngineError('Node must be a segment')
        parent = pop_to_parent_loop(seg_node)  # Get enclosing loop
        # check path for new loops to be added
        cur_path = self._path_list(parent.get_path())
        if self.last_path != cur_path:
            last_path = self.last_path
            match_idx = self._get_path_match_idx(last_path, cur_path)
            root_path = self._path_list(
                os.path.commonprefix(['/'.join(cur_path),
                                      '/'.join(last_path)]))
            if seg_node.is_first_seg_in_loop() and root_path == cur_path:
                match_idx -= 1
            for i in range(len(last_path) - 1, match_idx - 1, -1):
                self.writer.pop()
            for i in range(match_idx, len(cur_path)):
                (xname, attrib) = self._get_loop_info(cur_path[i])
                self.writer.push(xname, attrib)
        seg_node_id = self._get_node_id(seg_node, parent, seg_data)
        (xname, attrib) = self._get_seg_info(seg_node_id)
        self.writer.push(xname, attrib)
        for i in range(len(seg_data)):
            child_node = seg_node.get_child_node_by_idx(i)
            if child_node.usage == 'N' or seg_data.get('%02i' %
                                                       (i + 1)).is_empty():
                pass  # Do not try to ouput for invalid or empty elements
            elif child_node.is_composite():
                (xname, attrib) = self._get_comp_info(seg_node_id)
                self.writer.push(xname, attrib)
                comp_data = seg_data.get('%02i' % (i + 1))
                for j in range(len(comp_data)):
                    subele_node = child_node.get_child_node_by_idx(j)
                    (xname, attrib) = self._get_subele_info(subele_node.id)
                    self.writer.elem(xname, comp_data[j].get_value(), attrib)
                self.writer.pop()  # end composite
            elif child_node.is_element():
                if seg_data.get_value('%02i' % (i + 1)) == '':
                    pass
                    #self.writer.empty(u"ele", attrs={u'id': child_node.id})
                else:
                    (xname, attrib) = self._get_ele_info(child_node.id)
                    self.writer.elem(xname,
                                     seg_data.get_value('%02i' % (i + 1)),
                                     attrib)
            else:
                raise EngineError(
                    'Node must be a either an element or a composite')
        self.writer.pop()  # end segment
        self.last_path = cur_path

    def seg_context(self, seg_node, seg_data, pop_loops, push_loops):
        """
        Generate XML for the segment data and matching map node

        @param seg_node: Map Node
        @type seg_node: L{node<map_if.x12_node>}
        @param seg_data: Segment object
        @type seg_data: L{segment<segment.Segment>}
        """
        assert seg_node.is_segment(), 'Node must be a segment'
        parent = pop_to_parent_loop(seg_node)  # Get enclosing loop
        for loop in pop_loops:
            self.writer.pop()
        for loop in push_loops:
            (xname, attrib) = self._get_loop_info(loop.id)
            self.writer.push(xname, attrib)
        (xname, attrib) = self._get_seg_info(seg_node.id)
        self.writer.push(xname, attrib)
        for i in range(len(seg_data)):
            child_node = seg_node.get_child_node_by_idx(i)
            if child_node.usage == 'N' or seg_data.get('%02i' %
                                                       (i + 1)).is_empty():
                pass  # Do not try to ouput for invalid or empty elements
            elif child_node.is_composite():
                (xname, attrib) = self._get_comp_info(seg_node.id)
                self.writer.push(xname, attrib)
                comp_data = seg_data.get('%02i' % (i + 1))
                for j in range(len(comp_data)):
                    subele_node = child_node.get_child_node_by_idx(j)
                    (xname, attrib) = self._get_subele_info(subele_node.id)
                    self.writer.elem(xname, comp_data[j].get_value(), attrib)
                self.writer.pop()  # end composite
            elif child_node.is_element():
                if seg_data.get_value('%02i' % (i + 1)) == '':
                    pass
                    #self.writer.empty(u"ele", attrs={u'id': child_node.id})
                else:
                    (xname, attrib) = self._get_ele_info(child_node.id)
                    self.writer.elem(xname,
                                     seg_data.get_value('%02i' % (i + 1)),
                                     attrib)
            else:
                raise EngineError(
                    'Node must be a either an element or a composite')
        self.writer.pop()  # end segment

    def _path_list(self, path_str):
        """
        Get list of path nodes from path string
        @rtype: list
        """
        return [x for x in path_str.split('/') if x != '']

    def _get_path_match_idx(self, last_path, cur_path):
        """
        Get the index of the last matching path nodes
        """
        match_idx = 0
        for i in range(min(len(cur_path), len(last_path))):
            if cur_path[i] != last_path[i]:
                break
            match_idx += 1
        return match_idx

    def _get_node_id(self, seg_node, parent=None, seg_data=None):
        """
        Base node id function
        """
        return seg_node.id

    def _get_loop_info(self, loop_id):
        """
        Base loop node value
        """
        loop_name = loop_id
        attrib = {}
        return (loop_name, attrib)

    def _get_seg_info(self, seg_id):
        """
        Base segment node value
        """
        seg_name = seg_id
        attrib = {}
        return (seg_name, attrib)

    def _get_comp_info(self, comp_id):
        """
        Base composite node value
        """
        comp_name = comp_id
        attrib = {}
        return (comp_name, attrib)

    def _get_ele_info(self, ele_id):
        """
        Base element node value
        """
        name = ele_id
        attrib = {}
        return (name, attrib)

    def _get_subele_info(self, subele_id):
        """
        Base sub-element node value
        """
        name = subele_id
        attrib = {}
        return (name, attrib)
Esempio n. 18
0
class x12xml(object):
    def __init__(self, fd, type, dtd_urn):
        self.writer = XMLWriter(fd)
        if dtd_urn:
            self.writer.doctype(
                type, "-//J Holland//DTD XML X12 Document Conversion1.0//EN//XML",
                "%s" % (dtd_urn))
        self.writer.push(type)
        self.last_path = None

    def __del__(self):
        pass

    def seg(self, seg_node, seg_data):
        """
        Generate XML for the segment data and matching map node

        @param seg_node: Map Node
        @type seg_node: L{node<map_if.x12_node>}
        @param seg_data: Segment object
        @type seg_data: L{segment<segment.Segment>}
        """
        if not seg_node.is_segment():
            raise EngineError('Node must be a segment')
        parent = pop_to_parent_loop(seg_node)  # Get enclosing loop
        # check path for new loops to be added
        cur_path = self._path_list(parent.get_path())
        if self.last_path != cur_path:
            last_path = self.last_path
            match_idx = self._get_path_match_idx(last_path, cur_path)
            root_path = self._path_list(os.path.commonprefix(
                ['/'.join(cur_path), '/'.join(last_path)]))
            if seg_node.is_first_seg_in_loop() and root_path == cur_path:
                match_idx -= 1
            for i in range(len(last_path) - 1, match_idx - 1, -1):
                self.writer.pop()
            for i in range(match_idx, len(cur_path)):
                (xname, attrib) = self._get_loop_info(cur_path[i])
                self.writer.push(xname, attrib)
        seg_node_id = self._get_node_id(seg_node, parent, seg_data)
        (xname, attrib) = self._get_seg_info(seg_node_id)
        self.writer.push(xname, attrib)
        for i in range(len(seg_data)):
            child_node = seg_node.get_child_node_by_idx(i)
            if child_node.usage == 'N' or seg_data.get('%02i' % (i + 1)).is_empty():
                pass  # Do not try to ouput for invalid or empty elements
            elif child_node.is_composite():
                (xname, attrib) = self._get_comp_info(seg_node_id)
                self.writer.push(xname, attrib)
                comp_data = seg_data.get('%02i' % (i + 1))
                for j in range(len(comp_data)):
                    subele_node = child_node.get_child_node_by_idx(j)
                    (xname, attrib) = self._get_subele_info(subele_node.id)
                    self.writer.elem(xname, comp_data[j].get_value(), attrib)
                self.writer.pop()  # end composite
            elif child_node.is_element():
                if seg_data.get_value('%02i' % (i + 1)) == '':
                    pass
                    #self.writer.empty(u"ele", attrs={u'id': child_node.id})
                else:
                    (xname, attrib) = self._get_ele_info(child_node.id)
                    self.writer.elem(xname, seg_data.get_value(
                        '%02i' % (i + 1)), attrib)
            else:
                raise EngineError('Node must be a either an element or a composite')
        self.writer.pop()  # end segment
        self.last_path = cur_path

    def seg_context(self, seg_node, seg_data, pop_loops, push_loops):
        """
        Generate XML for the segment data and matching map node

        @param seg_node: Map Node
        @type seg_node: L{node<map_if.x12_node>}
        @param seg_data: Segment object
        @type seg_data: L{segment<segment.Segment>}
        """
        assert seg_node.is_segment(), 'Node must be a segment'
        parent = pop_to_parent_loop(seg_node)  # Get enclosing loop
        for loop in pop_loops:
            self.writer.pop()
        for loop in push_loops:
            (xname, attrib) = self._get_loop_info(loop.id)
            self.writer.push(xname, attrib)
        (xname, attrib) = self._get_seg_info(seg_node.id)
        self.writer.push(xname, attrib)
        for i in range(len(seg_data)):
            child_node = seg_node.get_child_node_by_idx(i)
            if child_node.usage == 'N' or seg_data.get('%02i' % (i + 1)).is_empty():
                pass  # Do not try to ouput for invalid or empty elements
            elif child_node.is_composite():
                (xname, attrib) = self._get_comp_info(seg_node.id)
                self.writer.push(xname, attrib)
                comp_data = seg_data.get('%02i' % (i + 1))
                for j in range(len(comp_data)):
                    subele_node = child_node.get_child_node_by_idx(j)
                    (xname, attrib) = self._get_subele_info(subele_node.id)
                    self.writer.elem(xname, comp_data[j].get_value(), attrib)
                self.writer.pop()  # end composite
            elif child_node.is_element():
                if seg_data.get_value('%02i' % (i + 1)) == '':
                    pass
                    #self.writer.empty(u"ele", attrs={u'id': child_node.id})
                else:
                    (xname, attrib) = self._get_ele_info(child_node.id)
                    self.writer.elem(xname, seg_data.get_value(
                        '%02i' % (i + 1)), attrib)
            else:
                raise EngineError('Node must be a either an element or a composite')
        self.writer.pop()  # end segment

    def _path_list(self, path_str):
        """
        Get list of path nodes from path string
        @rtype: list
        """
        return [x for x in path_str.split('/') if x != '']

    def _get_path_match_idx(self, last_path, cur_path):
        """
        Get the index of the last matching path nodes
        """
        match_idx = 0
        for i in range(min(len(cur_path), len(last_path))):
            if cur_path[i] != last_path[i]:
                break
            match_idx += 1
        return match_idx

    def _get_node_id(self, seg_node, parent=None, seg_data=None):
        """
        Base node id function
        """
        return seg_node.id

    def _get_loop_info(self, loop_id):
        """
        Base loop node value
        """
        loop_name = loop_id
        attrib = {}
        return (loop_name, attrib)

    def _get_seg_info(self, seg_id):
        """
        Base segment node value
        """
        seg_name = seg_id
        attrib = {}
        return (seg_name, attrib)

    def _get_comp_info(self, comp_id):
        """
        Base composite node value
        """
        comp_name = comp_id
        attrib = {}
        return (comp_name, attrib)

    def _get_ele_info(self, ele_id):
        """
        Base element node value
        """
        name = ele_id
        attrib = {}
        return (name, attrib)

    def _get_subele_info(self, subele_id):
        """
        Base sub-element node value
        """
        name = subele_id
        attrib = {}
        return (name, attrib)
Esempio n. 19
0
 def test_write_parameters_root_not_dict(self):
     parameters = ('shaun', 'juliet')
     writer = XMLWriter("root_not_dict.xml", "parameters", parameters)
     self.assertRaises(Exception, writer.write)