xml.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # -*- coding: utf-8 -*-
  2. # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)
  3. # 2020 MinIO, Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """XML utility module."""
  17. from __future__ import absolute_import, annotations
  18. import io
  19. from typing import Optional, Type, TypeVar
  20. from xml.etree import ElementTree as ET
  21. from typing_extensions import Protocol
  22. _S3_NAMESPACE = "http://s3.amazonaws.com/doc/2006-03-01/"
  23. def Element( # pylint: disable=invalid-name
  24. tag: str,
  25. namespace: str = _S3_NAMESPACE,
  26. ) -> ET.Element:
  27. """Create ElementTree.Element with tag and namespace."""
  28. return ET.Element(tag, {"xmlns": namespace} if namespace else {})
  29. def SubElement( # pylint: disable=invalid-name
  30. parent: ET.Element, tag: str, text: Optional[str] = None
  31. ) -> ET.Element:
  32. """Create ElementTree.SubElement on parent with tag and text."""
  33. element = ET.SubElement(parent, tag)
  34. if text is not None:
  35. element.text = text
  36. return element
  37. def _get_namespace(element: ET.Element) -> str:
  38. """Exact namespace if found."""
  39. start = element.tag.find("{")
  40. if start < 0:
  41. return ""
  42. start += 1
  43. end = element.tag.find("}")
  44. if end < 0:
  45. return ""
  46. return element.tag[start:end]
  47. def findall(element: ET.Element, name: str) -> list[ET.Element]:
  48. """Namespace aware ElementTree.Element.findall()."""
  49. namespace = _get_namespace(element)
  50. if namespace:
  51. name = "/".join(["ns:" + token for token in name.split("/")])
  52. return element.findall(name, {"ns": namespace} if namespace else {})
  53. def find(
  54. element: ET.Element,
  55. name: str,
  56. strict: bool = False,
  57. ) -> Optional[ET.Element]:
  58. """Namespace aware ElementTree.Element.find()."""
  59. namespace = _get_namespace(element)
  60. elem = element.find(
  61. "ns:" + name if namespace else name,
  62. {"ns": namespace} if namespace else {},
  63. )
  64. if strict and elem is None:
  65. raise ValueError(f"XML element <{name}> not found")
  66. return elem
  67. def findtext(
  68. element: ET.Element,
  69. name: str,
  70. strict: bool = False,
  71. ) -> Optional[str]:
  72. """
  73. Namespace aware ElementTree.Element.findtext() with strict flag
  74. raises ValueError if element name not exist.
  75. """
  76. elem = find(element, name, strict=strict)
  77. return None if elem is None else (elem.text or "")
  78. A = TypeVar("A")
  79. class FromXmlType(Protocol):
  80. """typing stub for class with `fromxml` method"""
  81. @classmethod
  82. def fromxml(cls: Type[A], element: ET.Element) -> A:
  83. """Create python object with values from XML element."""
  84. B = TypeVar("B", bound=FromXmlType)
  85. def unmarshal(cls: Type[B], xmlstring: str) -> B:
  86. """Unmarshal given XML string to an object of passed class."""
  87. return cls.fromxml(ET.fromstring(xmlstring))
  88. def getbytes(element: ET.Element) -> bytes:
  89. """Convert ElementTree.Element to bytes."""
  90. with io.BytesIO() as data:
  91. ET.ElementTree(element).write(
  92. data,
  93. encoding=None,
  94. xml_declaration=False,
  95. )
  96. return data.getvalue()
  97. class ToXmlType(Protocol):
  98. """typing stub for class with `toxml` method"""
  99. def toxml(self, element: Optional[ET.Element]) -> ET.Element:
  100. """Convert python object to ElementTree.Element."""
  101. def marshal(obj: ToXmlType) -> bytes:
  102. """Get XML data as bytes of ElementTree.Element."""
  103. return getbytes(obj.toxml(None))