Skip to content

Commit

Permalink
adding ability to get attributes for xpaths in specific namespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
jonrkarr committed Dec 31, 2020
1 parent b0e234e commit 341f948
Show file tree
Hide file tree
Showing 4 changed files with 5,569 additions and 6 deletions.
7 changes: 4 additions & 3 deletions biosimulators_utils/sedml/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,12 @@ def validate_data_generator_variable_xpaths(variables, model_source, attr='id'):
:obj:`dict` of :obj:`str` to :obj:`str`: dictionary that maps each XPath to the
value of the attribute of the object in the XML file that matches the XPath
"""
x_paths = []
target_x_paths = {}
for variable in variables:
if variable.target:
x_path = variable.target
if '/@' in x_path:
x_path, _, _ = x_path.rpartition('/@')
x_paths.append(x_path)
return validate_xpaths_ref_to_unique_objects(model_source, x_paths, attr=attr)
target_x_paths[variable.target] = x_path
x_path_attrs = validate_xpaths_ref_to_unique_objects(model_source, set(target_x_paths.values()), attr=attr)
return {target: x_path_attrs[x_path] for target, x_path in target_x_paths.items()}
9 changes: 6 additions & 3 deletions biosimulators_utils/xml/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def get_attributes_of_xpaths(filename, x_paths, attr='id'):
Args:
filename (:obj:`str`): path to XML file
x_paths (:obj:`list` of `str`): XPaths
attr (:obj:`str`, optional): attribute to get values of
attr (:obj:`str` or :obj:`dict`, optional): attribute to get values of
Returns:
:obj:`dict` of :obj:`str` to :obj:`list` of :obj:`str`: dictionary that maps each XPath to the
Expand All @@ -34,13 +34,16 @@ def get_attributes_of_xpaths(filename, x_paths, attr='id'):
if match:
namespaces[match.group(2)] = match.group(1)

if isinstance(attr, dict):
attr = '{{{}}}{}'.format(namespaces[attr['namespace']], attr['name'])

# determine number of objects that match each XPath
x_path_counts = {}
for x_path in x_paths:
try:
objects = etree.xpath(x_path, namespaces=namespaces)

x_path_counts[x_path] = [obj.attrib[attr] for obj in objects]
x_path_counts[x_path] = [obj.attrib.get(attr, None) for obj in objects]
except Exception:
x_path_counts[x_path] = []

Expand All @@ -54,7 +57,7 @@ def validate_xpaths_ref_to_unique_objects(filename, x_paths, attr='id'):
Args:
filename (:obj:`str`): path to XML file
x_paths (:obj:`list` of `str`): XPaths
attr (:obj:`str`, optional): attribute to get values of
attr (:obj:`str` or :obj:`dict`, optional): attribute to get values of
Returns:
:obj:`dict` of :obj:`str` to :obj:`str`: dictionary that maps each XPath to the
Expand Down
Loading

0 comments on commit 341f948

Please sign in to comment.