Python xml.dom.minidom.Node() Examples

The following are 16 code examples of xml.dom.minidom.Node(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.dom.minidom , or try the search function .
Example #1
Source File: agent.py    From psychsim with MIT License 6 votes vote down vote up
def __init__(self,name,world=None):
        self.world = world
        self.actions = set()
        self.legal = {}
        self.omega = True
#        self.O = True
        self.models = {}
        self.modelList = {}
        self.x = None
        self.y = None
        self.color = None
        if isinstance(name,Document):
            self.parse(name.documentElement)
        elif isinstance(name,Node):
            self.parse(name)
        else:
            self.name = name
        self.parallel = False
        self.epsilon = 1e-6 
Example #2
Source File: xform_instance_parser.py    From pyxform with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _xml_node_to_dict(node):
    assert isinstance(node, minidom.Node)
    if len(node.childNodes) == 0:
        # there's no data for this leaf node
        value = None
    elif len(node.childNodes) == 1 and node.childNodes[0].nodeType == node.TEXT_NODE:
        # there is data for this leaf node
        value = node.childNodes[0].nodeValue
    else:
        # this is an internal node
        value = {}
        for child in node.childNodes:
            d = _xml_node_to_dict(child)
            child_name = child.nodeName
            assert list(d.keys()) == [child_name]
            if child_name not in value:
                # copy the value into the dict
                value[child_name] = d[child_name]
            elif type(value[child_name]) == list:
                # add to the existing list
                value[child_name].append(d[child_name])
            else:
                # create a new list
                value[child_name] = [value[child_name], d[child_name]]
    return {node.nodeName: value} 
Example #3
Source File: matrix.py    From psychsim with MIT License 5 votes vote down vote up
def __init__(self,arg={}):
        self._keysIn = None
        self._keysOut = None
        if isinstance(arg,Node):
            try:
                super().__init__()
            except TypeError:
                super(KeyedMatrix,self).__init__()
            self.parse(arg)
        else:
            try:
                super().__init__(arg)
            except TypeError:
                super(KeyedMatrix,self).__init__(arg)
            self._string = None 
Example #4
Source File: tree.py    From psychsim with MIT License 5 votes vote down vote up
def __init__(self,leaf=None):
        self._string = None
        self._keysIn = None
        self._keysOut = None
        if isinstance(leaf,Node):
            self.parse(leaf)
        else:
            self.makeLeaf(leaf) 
Example #5
Source File: plane.py    From psychsim with MIT License 5 votes vote down vote up
def __init__(self,planes,threshold=None,comparison=None):
        """
        :warning: if S{planes} is a list, then S{threshold} and S{comparison} are ignored
        """
        if isinstance(planes,Node):
            self.parse(planes)
        elif isinstance(planes,KeyedVector):
            # Only a single branch passed
            if threshold is None:
                threshold = self.DEFAULT_THRESHOLD
            if comparison is None:
                comparison = self.DEFAULT_COMPARISON
            self.planes = [(planes,threshold,comparison)]
        else:
            self.planes = []
            for plane in planes:
                if len(plane) == 3:
                    self.planes.append(plane)
                elif len(plane) == 2:
                    self.planes.append((plane[0],plane[1],self.DEFAULT_COMPARISON))
                elif len(plane) == 1:
                    self.planes.append((plane[0],self.DEFAULT_THRESHOLD,self.DEFAULT_COMPARISON))
                else:
                    raise ValueError('Empty plane passed into constructor')
        self._string = None
        self._keys = None
        self.isConjunction = True 
Example #6
Source File: vector.py    From psychsim with MIT License 5 votes vote down vote up
def __init__(self,arg={}):
        collections.MutableMapping.__init__(self)
        self._data = {}
        self._string = None
        if isinstance(arg,Node):
            self.parse(arg)
        else:
            self._data.update(arg) 
Example #7
Source File: diagram.py    From psychsim with MIT License 5 votes vote down vote up
def __init__(self,args=None):
        self.x = {}
        self.y = {}
        self.color = {}
        if isinstance(args,Node):
            self.parse(args) 
Example #8
Source File: action.py    From psychsim with MIT License 5 votes vote down vote up
def __init__(self,arg={},description=None):
        if isinstance(arg,Node):
            dict.__init__(self)
            self.parse(arg)
        if isinstance(arg,str):
            values = arg.split('-')
            dict.__init__(self,{self.special[i]: values[i] for i in range(len(values))})
        else:
            dict.__init__(self,arg)
        self._string = None
        self.description = description 
Example #9
Source File: xform_instance_parser.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_meta_from_xml(xml_str, meta_name):
    xml = clean_and_parse_xml(xml_str)
    children = xml.childNodes
    # children ideally contains a single element
    # that is the parent of all survey elements
    if children.length == 0:
        raise ValueError(_("XML string must have a survey element."))
    survey_node = children[0]
    meta_tags = [n for n in survey_node.childNodes if
                 n.nodeType == Node.ELEMENT_NODE and
                 (n.tagName.lower() == "meta" or
                     n.tagName.lower() == "orx:meta")]
    if len(meta_tags) == 0:
        return None

    # get the requested tag
    meta_tag = meta_tags[0]
    uuid_tags = [n for n in meta_tag.childNodes if
                 n.nodeType == Node.ELEMENT_NODE and
                 (n.tagName.lower() == meta_name.lower() or
                  n.tagName.lower() == u'orx:%s' % meta_name.lower())]
    if len(uuid_tags) == 0:
        return None

    uuid_tag = uuid_tags[0]
    return uuid_tag.firstChild.nodeValue.strip() if uuid_tag.firstChild\
        else None 
Example #10
Source File: xmlmanager.py    From aws-extender with MIT License 5 votes vote down vote up
def save_list(self, doc, items, prop_node):
        items_node = doc.createElement('items')
        prop_node.appendChild(items_node)
        for item in items:
            item_node = doc.createElement('item')
            items_node.appendChild(item_node)
            if isinstance(item, Node):
                item_node.appendChild(item)
            else:
                text_node = doc.createTextNode(item)
                item_node.appendChild(text_node) 
Example #11
Source File: xmlmanager.py    From aws-extender with MIT License 5 votes vote down vote up
def marshal_object(self, obj, doc=None):
        if not doc:
            doc = self.new_doc()
        if not doc:
            doc = self.doc
        obj_node = doc.createElement('object')

        if obj.id:
            obj_node.setAttribute('id', obj.id)

        obj_node.setAttribute('class', '%s.%s' % (obj.__class__.__module__,
                                                  obj.__class__.__name__))
        root = doc.documentElement
        root.appendChild(obj_node)
        for property in obj.properties(hidden=False):
            prop_node = doc.createElement('property')
            prop_node.setAttribute('name', property.name)
            prop_node.setAttribute('type', property.type_name)
            value = property.get_value_for_datastore(obj)
            if value is not None:
                value = self.encode_value(property, value)
                if isinstance(value, list):
                    self.save_list(doc, value, prop_node)
                elif isinstance(value, Node):
                    prop_node.appendChild(value)
                else:
                    text_node = doc.createTextNode(six.text_type(value).encode("ascii", "ignore"))
                    prop_node.appendChild(text_node)
            obj_node.appendChild(prop_node)

        return doc 
Example #12
Source File: xmlmanager.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_list(self, doc, items, prop_node):
        items_node = doc.createElement('items')
        prop_node.appendChild(items_node)
        for item in items:
            item_node = doc.createElement('item')
            items_node.appendChild(item_node)
            if isinstance(item, Node):
                item_node.appendChild(item)
            else:
                text_node = doc.createTextNode(item)
                item_node.appendChild(text_node) 
Example #13
Source File: xmlmanager.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def marshal_object(self, obj, doc=None):
        if not doc:
            doc = self.new_doc()
        if not doc:
            doc = self.doc
        obj_node = doc.createElement('object')

        if obj.id:
            obj_node.setAttribute('id', obj.id)

        obj_node.setAttribute('class', '%s.%s' % (obj.__class__.__module__,
                                                  obj.__class__.__name__))
        root = doc.documentElement
        root.appendChild(obj_node)
        for property in obj.properties(hidden=False):
            prop_node = doc.createElement('property')
            prop_node.setAttribute('name', property.name)
            prop_node.setAttribute('type', property.type_name)
            value = property.get_value_for_datastore(obj)
            if value is not None:
                value = self.encode_value(property, value)
                if isinstance(value, list):
                    self.save_list(doc, value, prop_node)
                elif isinstance(value, Node):
                    prop_node.appendChild(value)
                else:
                    text_node = doc.createTextNode(unicode(value).encode("ascii", "ignore"))
                    prop_node.appendChild(text_node)
            obj_node.appendChild(prop_node)

        return doc 
Example #14
Source File: xmlclass.py    From OpenPLC_Editor with GNU General Public License v3.0 5 votes vote down vote up
def CreateNode(name):
    node = minidom.Node()
    node.nodeName = name
    node._attrs = {}
    node.childNodes = []
    return node 
Example #15
Source File: world.py    From psychsim with MIT License 4 votes vote down vote up
def __init__(self,xml=None,single=False):
        """
        :param xml: Initialization argument, either an XML Element, or a filename
        :type xml: Node or str
        :param single: If True, then there is no uncertainty about the state of this world (default is False)
        :type single: bool
        """
        self.agents = {}

        # State feature information
        if single:
            self.state = KeyedVector({CONSTANT: 1.})
        else:
            self.state = VectorDistributionSet()
        self.variables = {}
        self.locals = {}
        self.symbols = {}
        self.symbolList = []
        self.termination = []
        self.relations = {}

        # Turn order state info
        self.maxTurn = None
        self.turnSubstate = None
        self.turnKeys = set()

        # Action effect information
        self.dynamics = {}
        self.conditionalDynamics = {}
        self.newDynamics = {True: []}
        self.dependency = psychsim.graph.DependencyGraph(self)

        self.history = []

        self.diagram = None
        self.extras = {}

        if isinstance(xml,Node):
            self.parse(xml)
        elif isinstance(xml,str):
            if xml[-4:] == '.xml':
                # Uncompressed
                f = open(xml,'r')
            else:
                if xml[-4:] != '.psy':
                    xml = '%s.psy' % (xml)
                f = bz2.BZ2File(xml,'r')
            doc = parseString(f.read())
            f.close()
            self.parse(doc.documentElement)
        self.parallel = False 
Example #16
Source File: xform_instance_parser.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def _xml_node_to_dict(node, repeats=[]):
    assert isinstance(node, minidom.Node)
    if len(node.childNodes) == 0:
        # there's no data for this leaf node
        return None
    elif len(node.childNodes) == 1 and \
            node.childNodes[0].nodeType == node.TEXT_NODE:
        # there is data for this leaf node
        return {node.nodeName: node.childNodes[0].nodeValue}
    else:
        # this is an internal node
        value = {}
        for child in node.childNodes:

            # handle CDATA text section
            if child.nodeType == child.CDATA_SECTION_NODE:
                return {child.parentNode.nodeName: child.nodeValue}

            d = _xml_node_to_dict(child, repeats)
            if d is None:
                continue
            child_name = child.nodeName
            child_xpath = xpath_from_xml_node(child)
            assert d.keys() == [child_name]
            node_type = dict
            # check if name is in list of repeats and make it a list if so
            if child_xpath in repeats:
                node_type = list

            if node_type == dict:
                if child_name not in value:
                    value[child_name] = d[child_name]
                else:
                    # Duplicate Ona solution when repeating group is not present,
                    # but some nodes are still making references to it.
                    # Ref: https://github.com/onaio/onadata/commit/7d65fd30348b2f9c6ed6379c7bf79a523cc5750d
                    node_value = value[child_name]
                    # 1. check if the node values is a list
                    if not isinstance(node_value, list):
                        # if not a list, create one
                        value[child_name] = [node_value]
                    # 2. parse the node
                    d = _xml_node_to_dict(child, repeats)
                    # 3. aggregate
                    value[child_name].append(d[child_name])
            else:
                if child_name not in value:
                    value[child_name] = [d[child_name]]
                else:
                    value[child_name].append(d[child_name])
        if value == {}:
            return None
        else:
            return {node.nodeName: value}