|
2 | 2 | """DIDL-Lite (Digital Item Declaration Language) tools for Python.""" |
3 | 3 | # pylint: disable=too-many-lines |
4 | 4 |
|
| 5 | +import re |
5 | 6 | from typing import ( |
6 | 7 | Any, |
7 | 8 | Dict, |
@@ -1073,7 +1074,27 @@ def to_xml_string(*objects: DidlObject) -> bytes: |
1073 | 1074 | def from_xml_string( |
1074 | 1075 | xml_string: str, strict: bool = True |
1075 | 1076 | ) -> List[Union[DidlObject, Descriptor]]: |
1076 | | - """Convert XML string to DIDL Objects.""" |
| 1077 | + """Parse DIDL-Lite XML string.""" |
| 1078 | + if not strict: |
| 1079 | + # Find all prefixes used in tags, e.g., <prefix:tag ...> |
| 1080 | + used_prefixes = set(re.findall(r"<([a-zA-Z0-9]+):", xml_string)) |
| 1081 | + |
| 1082 | + # Find all defined namespaces, e.g., xmlns:prefix=... |
| 1083 | + defined_prefixes = set(re.findall(r"xmlns:([a-zA-Z0-9]+)=", xml_string)) |
| 1084 | + |
| 1085 | + # Identify prefixes used but not defined. |
| 1086 | + missing_prefixes = ( |
| 1087 | + used_prefixes - defined_prefixes - {"DIDL-Lite", "dc", "upnp", "dlna"} |
| 1088 | + ) |
| 1089 | + |
| 1090 | + # Remove the "if missing_prefixes:" line and just keep the for loop |
| 1091 | + for prefix in missing_prefixes: |
| 1092 | + dlna_ns = 'xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/"' |
| 1093 | + if dlna_ns in xml_string: |
| 1094 | + replacement = f'{dlna_ns} xmlns:{prefix}="http://tempuri.org/{prefix}/"' |
| 1095 | + xml_string = xml_string.replace(dlna_ns, replacement) |
| 1096 | + |
| 1097 | + # Proceed with parsing using the (potentially) patched xml_string |
1077 | 1098 | xml_el = defusedxml.ElementTree.fromstring(xml_string) |
1078 | 1099 | return from_xml_el(xml_el, strict) |
1079 | 1100 |
|
|
0 commit comments