getOrGeneratePrefix method
Returns the Prefix for a given namespace URI, generating a new one if not found.
This method first tries to find an existing prefix for the given namespace URI by checking the provided custom mappings and then the standard mappings. If no existing prefix is found, it attempts to generate a meaningful prefix based on the structure of the namespace URI.
Note that this will not change the immutable RdfNamespaceMappings instance. Instead, it will return a new prefix that can be used for custom mappings.
The returned tuple contains:
- The prefix: either an existing one or a newly generated one
- A boolean indicating whether the prefix was generated (true) or found (false)
The namespace
is the URI to look up or generate a prefix for, and
customMappings
are additional mappings to check before the standard ones.
Implementation
(String prefix, bool generated) getOrGeneratePrefix(
String namespace, {
Map<String, String> customMappings = const {},
}) {
String? candidate =
_getKeyByValue(customMappings, namespace) ??
_getKeyByValue(_mappings, namespace);
if (candidate != null) {
return (candidate, false);
}
// Generate a meaningful prefix from domain when possible
String? prefix = _tryGeneratePrefixFromUrl(namespace);
// Ensure prefix is not already used
if (prefix != null &&
!customMappings.containsKey(prefix) &&
!_mappings.containsKey(prefix)) {
return (prefix, true);
}
// Fall back to numbered prefixes
final computedPrefix = prefix ?? 'ns';
int prefixNum = 1;
do {
prefix = '$computedPrefix$prefixNum';
prefixNum++;
} while (customMappings.containsKey(prefix) &&
!_mappings.containsKey(prefix));
return (prefix, true);
}