Ejemplo n.º 1
0
 def test_namespace_substitution(self):
     xpath = XPath('/adrmsg:ADRMessage/adrmsg:hasMember[1]/aixm:Route/@{http://www.opengis.net/gml/3.2}id')
     short_xpath = XPath('/adrmsg:ADRMessage/adrmsg:hasMember[1]/aixm:Route/@gml:id')
     with self.subTest():
         self.assertEqual(short_xpath, xpath.shorten_namespaces(self.namespaces, in_place=False))
     with self.subTest():
         xpath.shorten_namespaces(self.namespaces, in_place=True)
         self.assertEqual(short_xpath, xpath)
Ejemplo n.º 2
0
def iter_map_xml_document_to_dict(xml_document: Path,
                                  xml_namespaces: Dict = None,
                                  json: Optional[Dict] = None,
                                  ignore_empty: bool = True) -> Iterator[Union[Dict, List]]:
    """
    Generator that iteratively maps each node encountered in the input xml_document.
    It will infer the output type for each node.
    :param xml_document: A Path to the XML document that is to be converted.
    :param xml_namespaces: A dictionary defining the XML namespaces with namespace shortname as keys
                           and the full namespace name as values. Follows the xml standard library
                           convention for XML namespaces.
    :param json: An input dictionary into which the XML document is to be mapped.
                 Defaults to an empty dictionary if none given.
    :param ignore_empty: A boolean indicating if missing XML Nodes should be ignored.
    :return: Yields a json serializable dictionary or list
    """
    json = json or {}
    xml_etree = xml_parse(str(xml_document))  # type: ElementTree
    root = xml_etree.getroot()
    root_xpath = XPath(xml_etree.getpath(root))
    all_elements = xml_etree.iterfind('//*')  # type: Iterable[ElementTree]

    for element in all_elements:
        ns_map = element.nsmap
        element_path = xml_etree.getpath(element)
        element_xpath = XPath(element_path)
        element_xpath.shorten_namespaces(ns_map, in_place=True).relative_to(root_xpath, in_place=True)
        attrib_paths = (XPath(f'{element_path}/@{attrib_name}') for attrib_name, _ in element.attrib.items())

        for attrib in attrib_paths:
            attrib.shorten_namespaces(ns_map, in_place=True)
            attrib.relative_to(root_xpath, in_place=True)
            yield attrib

    for node in generate_nodes(xml_etree, xml_namespaces):
        jsonize_mapping = node.to_jsonize(attributes='_')
        node_map: XMLNodeToJSONNode = parse_node_map(jsonize_mapping, transformations=[])
        node_map.map(xml_etree, json, xml_namespaces=xml_namespaces, ignore_empty=ignore_empty)
        yield json