(elem, default_namespace=None)
| 797 | yield file.write, encoding |
| 798 | |
| 799 | def _namespaces(elem, default_namespace=None): |
| 800 | # identify namespaces used in this tree |
| 801 | |
| 802 | # maps qnames to *encoded* prefix:local names |
| 803 | qnames = {None: None} |
| 804 | |
| 805 | # maps uri:s to prefixes |
| 806 | namespaces = {} |
| 807 | if default_namespace: |
| 808 | namespaces[default_namespace] = "" |
| 809 | |
| 810 | def add_qname(qname): |
| 811 | # calculate serialized qname representation |
| 812 | try: |
| 813 | if qname[:1] == "{": |
| 814 | uri, tag = qname[1:].rsplit("}", 1) |
| 815 | prefix = namespaces.get(uri) |
| 816 | if prefix is None: |
| 817 | prefix = _namespace_map.get(uri) |
| 818 | if prefix is None: |
| 819 | prefix = "ns%d" % len(namespaces) |
| 820 | if prefix != "xml": |
| 821 | namespaces[uri] = prefix |
| 822 | if prefix: |
| 823 | qnames[qname] = "%s:%s" % (prefix, tag) |
| 824 | else: |
| 825 | qnames[qname] = tag # default element |
| 826 | else: |
| 827 | if default_namespace: |
| 828 | # FIXME: can this be handled in XML 1.0? |
| 829 | raise ValueError( |
| 830 | "cannot use non-qualified names with " |
| 831 | "default_namespace option" |
| 832 | ) |
| 833 | qnames[qname] = qname |
| 834 | except TypeError: |
| 835 | _raise_serialization_error(qname) |
| 836 | |
| 837 | # populate qname and namespaces table |
| 838 | for elem in elem.iter(): |
| 839 | tag = elem.tag |
| 840 | if isinstance(tag, QName): |
| 841 | if tag.text not in qnames: |
| 842 | add_qname(tag.text) |
| 843 | elif isinstance(tag, str): |
| 844 | if tag not in qnames: |
| 845 | add_qname(tag) |
| 846 | elif tag is not None and tag is not Comment and tag is not PI: |
| 847 | _raise_serialization_error(tag) |
| 848 | for key, value in elem.items(): |
| 849 | if isinstance(key, QName): |
| 850 | key = key.text |
| 851 | if key not in qnames: |
| 852 | add_qname(key) |
| 853 | if isinstance(value, QName) and value.text not in qnames: |
| 854 | add_qname(value.text) |
| 855 | text = elem.text |
| 856 | if isinstance(text, QName) and text.text not in qnames: |
no test coverage detected
searching dependent graphs…