def xml_control(self): assert self.bind[u"type"] in [u"select", u"select1"] survey = self.get_root() control_dict = self.control.copy() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value) control_dict['ref'] = self.get_xpath() result = node(**control_dict) for element in self.xml_label_and_hint(): result.appendChild(element) # itemset are only supposed to be strings, # check to prevent the rare dicts that show up if self['itemset'] and isinstance(self['itemset'], basestring): choice_filter = self.get('choice_filter') itemset, file_extension = os.path.splitext(self['itemset']) if file_extension in ['.csv', '.xml']: itemset = itemset itemset_label_ref = "label" else: itemset = self['itemset'] itemset_label_ref = "jr:itext(itextId)" nodeset = "instance('" + itemset + "')/root/item" choice_filter = survey.insert_xpaths(choice_filter) if choice_filter: nodeset += '[' + choice_filter + ']' itemset_children = [node('value', ref='name'), node('label', ref=itemset_label_ref)] result.appendChild(node('itemset', *itemset_children, nodeset=nodeset)) else: for n in [o.xml() for o in self.children]: result.appendChild(n) return result
def xml(self): """ calls necessary preparation methods, then returns the xml. """ self.validate() self._setup_xpath_dictionary() for triggering_reference in self.setvalues_by_triggering_ref.keys(): if not (re.match(BRACKETED_TAG_REGEX, triggering_reference)): raise PyXFormError( "Only references to other fields are allowed in the 'trigger' column." ) # try to resolve reference and fail if can't self.insert_xpaths(triggering_reference, self) body_kwargs = {} if hasattr(self, constants.STYLE) and getattr(self, constants.STYLE): body_kwargs["class"] = getattr(self, constants.STYLE) nsmap = self.get_nsmap() return node( "h:html", node("h:head", node("h:title", self.title), self.xml_model()), node("h:body", *self.xml_control(), **body_kwargs), **nsmap )
def _generate_static_instances(list_name, choice_list): """ Generates <instance> elements for static data (e.g. choices for select type questions) Note that per commit message 0578242 and in xls2json.py R539, an instance is only output for select items defined in the choices sheet when the item has a choice_filter, and it is that way for backwards compatibility. """ instance_element_list = [] for idx, choice in enumerate(choice_list): choice_element_list = [] # Add a unique id to the choice element in case there is itext # it references itext_id = "-".join(["static_instance", list_name, str(idx)]) choice_element_list.append(node("itextId", itext_id)) for name, value in choice.items(): if isinstance(value, basestring) and name != "label": choice_element_list.append(node(name, unicode(value))) instance_element_list.append(node("item", *choice_element_list)) return InstanceInfo( type="choice", context="survey", name=list_name, src=None, instance=node( "instance", node("root", *instance_element_list), id=list_name ), )
def xml_control(self): """ <group> <label>Fav Color</label> <repeat nodeset="fav-color"> <select1 ref="."> <label ref="jr:itext('fav')" /> <item><label ref="jr:itext('red')" /><value>red</value></item> <item><label ref="jr:itext('green')" /><value>green</value></item> <item><label ref="jr:itext('blue')" /><value>blue</value></item> </select1> </repeat> </group> """ control_dict = self.control.copy() survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) repeat_node = node("repeat", nodeset=self.get_xpath(), **control_dict) for n in Section.xml_control(self): repeat_node.appendChild(n) label = self.xml_label() if label: return node("group", self.xml_label(), repeat_node, ref=self.get_xpath()) return node("group", repeat_node, ref=self.get_xpath(), **self.control)
def xml_model(self): """ Generate the xform <model> element """ self._setup_translations() self._setup_media() self._add_empty_translations() model_children = [] if self._translations: model_children.append(self.itext()) model_children += [node("instance", self.xml_instance())] model_children += list(self._generate_instances()) model_children += self.xml_bindings() model_children += self.xml_actions() if self.submission_url or self.public_key or self.auto_send or self.auto_delete: submission_attrs = dict() if self.submission_url: submission_attrs["action"] = self.submission_url submission_attrs["method"] = "post" if self.public_key: submission_attrs["base64RsaPublicKey"] = self.public_key if self.auto_send: submission_attrs["orx:auto-send"] = self.auto_send if self.auto_delete: submission_attrs["orx:auto-delete"] = self.auto_delete submission_node = node("submission", **submission_attrs) model_children.insert(0, submission_node) return node("model", *model_children)
def xml_control(self): """ <group> <label>Fav Color</label> <repeat nodeset="fav-color"> <select1 ref="."> <label ref="jr:itext('fav')" /> <item><label ref="jr:itext('red')" /><value>red</value></item> <item><label ref="jr:itext('green')" /><value>green</value></item> <item><label ref="jr:itext('blue')" /><value>blue</value></item> </select1> </repeat> </group> """ control_dict = self.control.copy() survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value) repeat_node = node(u"repeat", nodeset=self.get_xpath(), **control_dict) for n in Section.xml_control(self): repeat_node.appendChild(n) label = self.xml_label() if label: return node( u"group", self.xml_label(), repeat_node, ref=self.get_xpath() ) return node(u"group", repeat_node, ref=self.get_xpath(), **self.control)
def xml_model(self): """ Generate the xform <model> element """ self._setup_translations() self._setup_media() self._add_empty_translations() model_children = [] if self._translations: model_children.append(self.itext()) model_children += [node("instance", self.xml_instance())] model_children += list(self._generate_instances()) model_children += self.xml_bindings() if self.submission_url or self.public_key: submission_attrs = dict() if self.submission_url: submission_attrs["action"] = self.submission_url if self.public_key: submission_attrs["base64RsaPublicKey"] = self.public_key submission_node = node("submission", method="form-data-post", **submission_attrs) model_children.insert(0, submission_node) return node("model", *model_children)
def xml_model(self): """ Generate the xform <model> element """ self._setup_translations() self._setup_media() self._add_empty_translations() model_children = [] if self._translations: model_children.append(self.itext()) model_children += [node("instance", self.xml_instance())] model_children += list(self._generate_static_instances()) model_children += list(self._generate_pulldata_instances()) model_children += list(self._generate_from_file_instances()) model_children += self.xml_bindings() if self.submission_url or self.public_key: submission_attrs = dict() if self.submission_url: submission_attrs["action"] = self.submission_url if self.public_key: submission_attrs["base64RsaPublicKey"] = self.public_key submission_node = node("submission", method="form-data-post", **submission_attrs) model_children.insert(0, submission_node) return node("model", *model_children)
def _generate_static_instances(self): """ Generates <instance> elements for static data (e.g. choices for select type questions) """ for list_name, choice_list in self.choices.items(): instance_element_list = [] for idx, choice in zip(range(len(choice_list)), choice_list): choice_element_list = [] # Add a unique id to the choice element incase there is itext # it refrences itext_id = '-'.join(['static_instance', list_name, str(idx)]) choice_element_list.append(node("itextId", itext_id)) for choicePropertyName, choicePropertyValue in choice.items(): if isinstance(choicePropertyValue, basestring) \ and choicePropertyName != 'label': choice_element_list.append( node(choicePropertyName, unicode(choicePropertyValue))) instance_element_list.append(node("item", *choice_element_list)) yield node("instance", node("root", *instance_element_list), id=list_name)
def _generate_static_instances(list_name, choice_list): """ Generates <instance> elements for static data (e.g. choices for select type questions) Note that per commit message 0578242 and in xls2json.py R539, an instance is only output for select items defined in the choices sheet when the item has a choice_filter, and it is that way for backwards compatibility. """ instance_element_list = [] for idx, choice in enumerate(choice_list): choice_element_list = [] # Add a unique id to the choice element in case there is itext # it references itext_id = '-'.join(['static_instance', list_name, str(idx)]) choice_element_list.append(node("itextId", itext_id)) for choicePropertyName, choicePropertyValue in choice.items(): if isinstance(choicePropertyValue, basestring) \ and choicePropertyName != 'label': choice_element_list.append( node(choicePropertyName, unicode(choicePropertyValue))) instance_element_list.append(node("item", *choice_element_list)) return InstanceInfo(type=u"choice", context=u"survey", name=list_name, src=None, instance=node("instance", node("root", *instance_element_list), id=list_name))
def xml_control(self): assert self.bind[u"type"] in [u"select", u"select1", u"odk:rank"] survey = self.get_root() control_dict = self.control.copy() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() result = node(**control_dict) for element in self.xml_label_and_hint(): result.appendChild(element) # itemset are only supposed to be strings, # check to prevent the rare dicts that show up if self["itemset"] and isinstance(self["itemset"], basestring): choice_filter = self.get("choice_filter") itemset, file_extension = os.path.splitext(self["itemset"]) if file_extension in [".csv", ".xml"]: itemset = itemset itemset_label_ref = "label" else: itemset = self["itemset"] itemset_label_ref = "jr:itext(itextId)" nodeset = "instance('" + itemset + "')/root/item" choice_filter = survey.insert_xpaths(choice_filter, self, True) if choice_filter: nodeset += "[" + choice_filter + "]" if self["parameters"]: params = self["parameters"] if "randomize" in params and params["randomize"] == "true": nodeset = "randomize(" + nodeset if "seed" in params: if params["seed"].startswith("${"): nodeset = ( nodeset + ", " + survey.insert_xpaths( params["seed"], self ).strip() ) else: nodeset = nodeset + ", " + params["seed"] nodeset += ")" itemset_children = [ node("value", ref="name"), node("label", ref=itemset_label_ref), ] result.appendChild( node("itemset", *itemset_children, nodeset=nodeset) ) else: for n in [o.xml() for o in self.children]: result.appendChild(n) return result
def xml_hint(self): if type(self.hint) == dict: path = self._translation_path("hint") return node(u"hint", ref="jr:itext('%s')" % path) else: hint, output_inserted = self.get_root().insert_output_values( self.hint) return node(u"hint", hint, toParseString=output_inserted)
def xml_hint(self): if isinstance(self.hint, dict) or self.guidance_hint: path = self._translation_path("hint") return node("hint", ref="jr:itext('%s')" % path) else: hint, output_inserted = self.get_root().insert_output_values( self.hint, self) return node("hint", hint, toParseString=output_inserted)
def xml_hint(self): if isinstance(self.hint, dict) or self.guidance_hint: path = self._translation_path("hint") return node("hint", ref="jr:itext('%s')" % path) else: hint, output_inserted = self.get_root().insert_output_values( self.hint, self ) return node("hint", hint, toParseString=output_inserted)
def xml_instance(self): survey = self.get_root() attributes = {} attributes.update(self.get(u'instance', {})) for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value) if self.get(u"default"): return node(self.name, unicode(self.get(u"default")), **attributes) return node(self.name, **attributes)
def xml_instance(self, **kwargs): survey = self.get_root() attributes = {} attributes.update(self.get("instance", {})) for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value, self) if self.get("default"): return node(self.name, unicode(self.get("default")), **attributes) return node(self.name, **attributes)
def xml_label(self): if self.needs_itext_ref(): # If there is a dictionary label, or non-empty media dict, # then we need to make a label with an itext ref ref = "jr:itext('%s')" % self._translation_path(u"label") return node(u"label", ref=ref) else: survey = self.get_root() label, output_inserted = survey.insert_output_values(self.label) return node(u"label", label, toParseString=output_inserted)
def xml_instance(self, **kwargs): survey = self.get_root() attributes = {} attributes.update(self.get("instance", {})) for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value, self) if self.get("default") and not default_is_dynamic(self.default, self.type): return node(self.name, unicode(self.get("default")), **attributes) return node(self.name, **attributes)
def xml_control(self): assert self.bind["type"] in ["select", "select1", "odk:rank"] survey = self.get_root() control_dict = self.control.copy() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() result = node(**control_dict) for element in self.xml_label_and_hint(): result.appendChild(element) # itemset are only supposed to be strings, # check to prevent the rare dicts that show up if self["itemset"] and isinstance(self["itemset"], basestring): choice_filter = self.get("choice_filter") itemset, file_extension = os.path.splitext(self["itemset"]) if file_extension in [".csv", ".xml"]: itemset = itemset itemset_label_ref = "label" else: itemset = self["itemset"] itemset_label_ref = "jr:itext(itextId)" nodeset = "instance('" + itemset + "')/root/item" choice_filter = survey.insert_xpaths(choice_filter, self, True) if choice_filter: nodeset += "[" + choice_filter + "]" if self["parameters"]: params = self["parameters"] if "randomize" in params and params["randomize"] == "true": nodeset = "randomize(" + nodeset if "seed" in params: if params["seed"].startswith("${"): nodeset = ( nodeset + ", " + survey.insert_xpaths(params["seed"], self).strip() ) else: nodeset = nodeset + ", " + params["seed"] nodeset += ")" itemset_children = [ node("value", ref="name"), node("label", ref=itemset_label_ref), ] result.appendChild(node("itemset", *itemset_children, nodeset=nodeset)) else: for n in [o.xml() for o in self.children]: result.appendChild(n) return result
def _generate_from_file_instances(self): for i in self.iter_descendants(): itemset = i.get('itemset') if itemset and \ (itemset.endswith('.csv') or itemset.endswith('.xml')): file_id, file_extension = os.path.splitext(itemset) yield node("instance", node("root", node("item", node("name"), node("label"))), id=file_id, src="jr://file-%s/%s" % (file_extension[1:], itemset))
def xml_control(self): assert self.bind[u"type"] in [u"select", u"select1", u"odk:rank"] survey = self.get_root() control_dict = self.control.copy() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value) control_dict['ref'] = self.get_xpath() result = node(**control_dict) for element in self.xml_label_and_hint(): result.appendChild(element) # itemset are only supposed to be strings, # check to prevent the rare dicts that show up if self['itemset'] and isinstance(self['itemset'], basestring): choice_filter = self.get('choice_filter') itemset, file_extension = os.path.splitext(self['itemset']) if file_extension in ['.csv', '.xml']: itemset = itemset itemset_label_ref = "label" else: itemset = self['itemset'] itemset_label_ref = "jr:itext(itextId)" nodeset = "instance('" + itemset + "')/root/item" choice_filter = survey.insert_xpaths(choice_filter) if choice_filter: nodeset += '[' + choice_filter + ']' if self['parameters']: params = self['parameters'] if 'randomize' in params and params['randomize'] == 'true': nodeset = 'randomize(' + nodeset if 'seed' in params: nodeset = nodeset + ', ' + params['seed'] nodeset += ')' itemset_children = [ node('value', ref='name'), node('label', ref=itemset_label_ref) ] result.appendChild( node('itemset', *itemset_children, nodeset=nodeset)) else: for n in [o.xml() for o in self.children]: result.appendChild(n) return result
def _generate_from_file_instances(self): for i in self.iter_descendants(): itemset = i.get('itemset') if itemset and \ (itemset.endswith('.csv') or itemset.endswith('.xml')): file_id, ext = os.path.splitext(itemset) uri = 'jr://%s/%s' % ('file' if ext == '.xml' else "file-%s" % ext[1:], itemset) yield node("instance", node( "root", node("item", node("name", "_"), node("label", "_"))), id=file_id, src=uri)
def xml(self): """ calls necessary preparation methods, then returns the xml. """ self.validate() self._setup_xpath_dictionary() body_kwargs = {} if hasattr(self, constants.STYLE) and getattr(self, constants.STYLE): body_kwargs["class"] = getattr(self, constants.STYLE) nsmap = self.get_nsmap() return node( "h:html", node("h:head", node("h:title", self.title), self.xml_model()), node("h:body", *self.xml_control(), **body_kwargs), **nsmap)
def xml(self): item = node("item") self.xml_label() item.appendChild(self.xml_label()) item.appendChild(self.xml_value()) return item
def xml_control(self): control_dict = self.control if control_dict.get("bodyless"): return None children = [] attributes = {} attributes.update(self.control) survey = self.get_root() # Resolve field references in attributes for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value) if not self.get('flat'): attributes['ref'] = self.get_xpath() if 'label' in self and len(self['label']) > 0: children.append(self.xml_label()) for n in Section.xml_control(self): children.append(n) if u"appearance" in control_dict: attributes['appearance'] = control_dict['appearance'] if u"intent" in control_dict: survey = self.get_root() attributes['intent'] = survey.insert_xpaths(control_dict['intent']) return node(u"group", *children, **attributes)
def _generate_pulldata_instances(element): if "calculate" in element["bind"]: calculate = element["bind"]["calculate"] if calculate.startswith("pulldata("): pieces = ( calculate.split('"') if '"' in calculate else calculate.split("'") ) if len(pieces) > 1 and pieces[1]: file_id = pieces[1] uri = "jr://file-csv/{}.csv".format(file_id) return InstanceInfo( type="pulldata", context="[type: {t}, name: {n}]".format( t=element["parent"]["type"], n=element["parent"]["name"] ), name=file_id, src=uri, instance=node( "instance", Survey._get_dummy_instance(), id=file_id, src=uri, ), ) return None
def xml_control(self): control_dict = self.control if control_dict.get("bodyless"): return None children = [] attributes = {} attributes.update(self.control) survey = self.get_root() # Resolve field references in attributes for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value, self) if not self.get("flat"): attributes["ref"] = self.get_xpath() if "label" in self and len(self["label"]) > 0: children.append(self.xml_label()) for n in Section.xml_control(self): children.append(n) if "appearance" in control_dict: attributes["appearance"] = control_dict["appearance"] if "intent" in control_dict: survey = self.get_root() attributes["intent"] = survey.insert_xpaths(control_dict["intent"], self) return node("group", *children, **attributes)
def xml_binding(self): """ Return the binding for this survey element. """ survey = self.get_root() bind_dict = self.bind.copy() if self.get('flat'): # Don't generate bind element for flat groups. return None if bind_dict: for k, v in bind_dict.items(): # I think all the binding conversions should be happening on # the xls2json side. if hashable(v) and v in self.binding_conversions: v = self.binding_conversions[v] if k == u'jr:constraintMsg' and type(v) is dict: v = "jr:itext('%s')" % self._translation_path( u'jr:constraintMsg') if k == u'jr:requiredMsg' and type(v) is dict: v = "jr:itext('%s')" % self._translation_path( u'jr:requiredMsg') if k == u'jr:noAppErrorString' and type(v) is dict: v = "jr:itext('%s')" % self._translation_path( u'jr:noAppErrorString') bind_dict[k] = survey.insert_xpaths(v) return node(u"bind", nodeset=self.get_xpath(), **bind_dict) return None
def xml_control(self): control_dict = self.control if control_dict.get("bodyless"): return None children = [] attributes = {} attributes.update(self.control) survey = self.get_root() # Resolve field references in attributes for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value, self) if not self.get("flat"): attributes["ref"] = self.get_xpath() if "label" in self and len(self["label"]) > 0: children.append(self.xml_label()) for n in Section.xml_control(self): children.append(n) if "appearance" in control_dict: attributes["appearance"] = control_dict["appearance"] if "intent" in control_dict: survey = self.get_root() attributes["intent"] = survey.insert_xpaths( control_dict["intent"], self) return node("group", *children, **attributes)
def xml_binding(self): """ Return the binding for this survey element. """ survey = self.get_root() bind_dict = self.bind.copy() if self.get("flat"): # Don't generate bind element for flat groups. return None if bind_dict: # the expression goes in a setvalue action if self.trigger and "calculate" in self.bind: del bind_dict["calculate"] for k, v in bind_dict.items(): # I think all the binding conversions should be happening on # the xls2json side. if (hashable(v) and v in self.binding_conversions and k in self.CONVERTIBLE_BIND_ATTRIBUTES): v = self.binding_conversions[v] if k == "jr:constraintMsg" and (type(v) is dict or re.search( BRACKETED_TAG_REGEX, v)): v = "jr:itext('%s')" % self._translation_path( "jr:constraintMsg") if k == "jr:requiredMsg" and (type(v) is dict or re.search( BRACKETED_TAG_REGEX, v)): v = "jr:itext('%s')" % self._translation_path( "jr:requiredMsg") if k == "jr:noAppErrorString" and type(v) is dict: v = "jr:itext('%s')" % self._translation_path( "jr:noAppErrorString") bind_dict[k] = survey.insert_xpaths(v, context=self) return node("bind", nodeset=self.get_xpath(), **bind_dict) return None
def _generate_pulldata_instances(element): if "calculate" in element["bind"]: calculate = element["bind"]["calculate"] if calculate.startswith("pulldata("): pieces = (calculate.split('"') if '"' in calculate else calculate.split("'")) if len(pieces) > 1 and pieces[1]: file_id = pieces[1] uri = "jr://file-csv/{}.csv".format(file_id) return InstanceInfo( type="pulldata", context="[type: {t}, name: {n}]".format( t=element["parent"]["type"], n=element["parent"]["name"]), name=file_id, src=uri, instance=node( "instance", Survey._get_dummy_instance(), id=file_id, src=uri, ), ) return None
def xml_instance(self, **kwargs): """ Creates an xml representation of the section """ append_template = kwargs.pop("append_template", False) attributes = {} attributes.update(kwargs) attributes.update(self.get("instance", {})) survey = self.get_root() # Resolve field references in attributes for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value, self) result = node(self.name, **attributes) for child in self.children: repeating_template = None if child.get("flat"): for grandchild in child.xml_instance_array(): result.appendChild(grandchild) elif isinstance(child, ExternalInstance): continue else: if isinstance(child, RepeatingSection) and not append_template: append_template = not append_template repeating_template = child.generate_repeating_template() result.appendChild( child.xml_instance(append_template=append_template)) if append_template and repeating_template: append_template = not append_template result.insertBefore(repeating_template, result._get_lastChild()) return result
def build_xml(self): control_dict = self.control survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() return node("trigger", *self.xml_label_and_hint(), **control_dict)
def xml(self): result = node("tag", key=self.name) self.xml_label() result.appendChild(self.xml_label()) for choice in self.children: result.appendChild(choice.xml()) return result
def xml(self): """ calls necessary preparation methods, then returns the xml. """ self.validate() self._setup_xpath_dictionary() body_kwargs = {} if hasattr(self, constants.STYLE) and getattr(self, constants.STYLE): body_kwargs["class"] = getattr(self, constants.STYLE) nsmap = self.get_nsmap() return node( "h:html", node("h:head", node("h:title", self.title), self.xml_model()), node("h:body", *self.xml_control(), **body_kwargs), **nsmap )
def xml_control(self): control_dict = self.control survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() return node("trigger", *self.xml_label_and_hint(), **control_dict)
def xml_control(self): control_dict = self.control control_dict['ref'] = self.get_xpath() control_dict['mediatype'] = self._get_media_type() return node( u"upload", *self.xml_label_and_hint(), **control_dict )
def generate_repeating_template(self, **kwargs): attributes = {"jr:template": ""} result = node(self.name, **attributes) for child in self.children: if isinstance(child, RepeatingSection): result.appendChild(child.template_instance()) else: result.appendChild(child.xml_instance()) return result
def xml_control(self): control_dict = self.control survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() control_dict["mediatype"] = self._get_media_type() return node("upload", *self.xml_label_and_hint(), **control_dict)
def xml_dynamic_default(self, in_binding=False): if not self.default or not default_is_dynamic(self.default, self.type): return if self.parent.__class__.__name__ == "Survey" and in_binding: default_handler = {"event": "odk-instance-first-load"} return node("setvalue", ref=self.get_xpath(), value=self.default, **default_handler) if self.parent.__class__.__name__ != "Survey" and not in_binding: default_handler = { "event": "odk-instance-first-load odk-new-repeat" } return node("setvalue", ref=self.get_xpath(), value=self.default, **default_handler)
def xml_control(self): control_dict = self.control control_dict["ref"] = self.get_xpath() control_dict["mediatype"] = self._get_media_type() result = node("upload", *self.xml_label_and_hint(), **control_dict) for osm_tag in self.children: result.appendChild(osm_tag.xml()) return result
def build_xml(self): control_dict = self.control control_dict["ref"] = self.get_xpath() control_dict["mediatype"] = self._get_media_type() result = node("upload", *self.xml_label_and_hint(), **control_dict) for osm_tag in self.children: result.appendChild(osm_tag.xml()) return result
def xml_control(self): control_dict = self.control label_and_hint = self.xml_label_and_hint() survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() params = self.get("parameters", {}) control_dict.update(params) result = node(**control_dict) if label_and_hint: for element in self.xml_label_and_hint(): result.appendChild(element) return result
def _generate_external_instances(element): if isinstance(element, ExternalInstance): name = element["name"] src = "jr://file/{}.xml".format(name) return InstanceInfo( type="external", context="[type: {t}, name: {n}]".format( t=element["parent"]["type"], n=element["parent"]["name"] ), name=name, src=src, instance=node( "instance", Survey._get_dummy_instance(), id=name, src=src ), ) return None
def xml_instance(self, **kwargs): """ Creates an xml representation of the section """ attributes = {} attributes.update(kwargs) attributes.update(self.get(u'instance', {})) survey = self.get_root() # Resolve field references in attributes for key, value in attributes.items(): attributes[key] = survey.insert_xpaths(value) result = node(self.name, **attributes) for child in self.children: if child.get(u"flat"): for grandchild in child.xml_instance_array(): result.appendChild(grandchild) elif isinstance(child, ExternalInstance): continue else: result.appendChild(child.xml_instance()) return result
def _generate_from_file_instances(element): itemset = element.get("itemset") if itemset and (itemset.endswith(".csv") or itemset.endswith(".xml")): file_id, ext = os.path.splitext(itemset) uri = "jr://%s/%s" % ( "file" if ext == ".xml" else "file-%s" % ext[1:], itemset, ) return InstanceInfo( type="file", context="[type: {t}, name: {n}]".format( t=element["parent"]["type"], n=element["parent"]["name"] ), name=file_id, src=uri, instance=node( "instance", Survey._get_dummy_instance(), id=file_id, src=uri ), ) return None
def _generate_from_file_instances(element): itemset = element.get('itemset') if itemset and (itemset.endswith('.csv') or itemset.endswith('.xml')): file_id, ext = os.path.splitext(itemset) uri = 'jr://%s/%s' % ( 'file' if ext == '.xml' else "file-%s" % ext[1:], itemset) return InstanceInfo( type=u"file", context="[type: {t}, name: {n}]".format( t=element[u"parent"][u"type"], n=element[u"parent"][u"name"] ), name=file_id, src=uri, instance=node( "instance", Survey._get_dummy_instance(), id=file_id, src=uri ) )
def xml_control(self): control_dict = self.control label_and_hint = self.xml_label_and_hint() survey = self.get_root() # Resolve field references in attributes for key, value in control_dict.items(): control_dict[key] = survey.insert_xpaths(value, self) control_dict["ref"] = self.get_xpath() result = node(**control_dict) if label_and_hint: for element in self.xml_label_and_hint(): result.appendChild(element) # Input types are used for selects with external choices sheets. if self["query"]: choice_filter = self.get("choice_filter") query = "instance('" + self["query"] + "')/root/item" choice_filter = survey.insert_xpaths(choice_filter, self, True) if choice_filter: query += "[" + choice_filter + "]" result.setAttribute("query", query) return result
def _generate_pulldata_instances(element): if 'calculate' in element['bind']: calculate = element['bind']['calculate'] if calculate.startswith('pulldata('): pieces = calculate.split('"') \ if '"' in calculate else calculate.split("'") if len(pieces) > 1 and pieces[1]: file_id = pieces[1] uri = "jr://file-csv/{}.csv".format(file_id) return InstanceInfo( type=u"pulldata", context="[type: {t}, name: {n}]".format( t=element[u"parent"][u"type"], n=element[u"parent"][u"name"] ), name=file_id, src=uri, instance=node( "instance", Survey._get_dummy_instance(), id=file_id, src=uri ) )
def xml_value(self): return node("value", self.name)
def itext(self): """ This function creates the survey's itext nodes from _translations @see _setup_media _setup_translations itext nodes are localized images/audio/video/text @see http://code.google.com/p/opendatakit/wiki/XFormDesignGuidelines """ result = [] for lang, translation in self._translations.items(): if lang == self.default_language: result.append( node("translation", lang=lang, default=u"true()")) else: result.append(node("translation", lang=lang)) for label_name, content in translation.items(): itext_nodes = [] label_type = label_name.partition(":")[-1] if type(content) is not dict: raise Exception() for media_type, media_value in content.items(): # There is a odk/jr bug where hints can't have a value # for the "form" attribute. # This is my workaround. if label_type == u"hint": value, output_inserted = \ self.insert_output_values(media_value) itext_nodes.append( node("value", value, toParseString=output_inserted) ) continue if media_type == "long": value, output_inserted = \ self.insert_output_values(media_value) # I'm ignoring long types for now because I don't know # how they are supposed to work. itext_nodes.append( node("value", value, toParseString=output_inserted) ) elif media_type == "image": value, output_inserted = \ self.insert_output_values(media_value) itext_nodes.append( node("value", "jr://images/" + value, form=media_type, toParseString=output_inserted) ) else: value, output_inserted = \ self.insert_output_values(media_value) itext_nodes.append( node("value", "jr://" + media_type + "/" + value, form=media_type, toParseString=output_inserted)) result[-1].appendChild( node("text", *itext_nodes, id=label_name)) return node("itext", *result)
def test_patch_lets_node_func_escape_only_necessary(self): """Should only escape text chars that should be: ["<", ">", "&"].""" text = u"' \" & < >" expected = u"<root>' \" & < ></root>".format(text) observed = node(u"root", text).toprettyxml(indent="", newl="") self.assertEqual(expected, observed)
def _get_dummy_instance(): """Instance content required by ODK Validate for select inputs.""" return node("root", node("item", node("name", "_"), node("label", "_")))