utilities.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/env python3
  2. """
  3. Utilities for editing OOXML documents.
  4. This module provides XMLEditor, a tool for manipulating XML files with support for
  5. line-number-based node finding and DOM manipulation. Each element is automatically
  6. annotated with its original line and column position during parsing.
  7. Example usage:
  8. editor = XMLEditor("document.xml")
  9. # Find node by line number or range
  10. elem = editor.get_node(tag="w:r", line_number=519)
  11. elem = editor.get_node(tag="w:p", line_number=range(100, 200))
  12. # Find node by text content
  13. elem = editor.get_node(tag="w:p", contains="specific text")
  14. # Find node by attributes
  15. elem = editor.get_node(tag="w:r", attrs={"w:id": "target"})
  16. # Combine filters
  17. elem = editor.get_node(tag="w:p", line_number=range(1, 50), contains="text")
  18. # Replace, insert, or manipulate
  19. new_elem = editor.replace_node(elem, "<w:r><w:t>new text</w:t></w:r>")
  20. editor.insert_after(new_elem, "<w:r><w:t>more</w:t></w:r>")
  21. # Save changes
  22. editor.save()
  23. """
  24. import html
  25. from pathlib import Path
  26. import defusedxml.minidom
  27. import defusedxml.sax
  28. class XMLEditor:
  29. """
  30. Editor for manipulating OOXML XML files with line-number-based node finding.
  31. This class parses XML files and tracks the original line and column position
  32. of each element. This enables finding nodes by their line number in the original
  33. file, which is useful when working with Read tool output.
  34. Attributes:
  35. xml_path: Path to the XML file being edited
  36. encoding: Detected encoding of the XML file ('ascii' or 'utf-8')
  37. dom: Parsed DOM tree with parse_position attributes on elements
  38. """
  39. def __init__(self, xml_path):
  40. """
  41. Initialize with path to XML file and parse with line number tracking.
  42. Args:
  43. xml_path: Path to XML file to edit (str or Path)
  44. Raises:
  45. ValueError: If the XML file does not exist
  46. """
  47. self.xml_path = Path(xml_path)
  48. if not self.xml_path.exists():
  49. raise ValueError(f"XML file not found: {xml_path}")
  50. with open(self.xml_path, "rb") as f:
  51. header = f.read(200).decode("utf-8", errors="ignore")
  52. self.encoding = "ascii" if 'encoding="ascii"' in header else "utf-8"
  53. parser = _create_line_tracking_parser()
  54. self.dom = defusedxml.minidom.parse(str(self.xml_path), parser)
  55. def get_node(
  56. self,
  57. tag: str,
  58. attrs: dict[str, str] | None = None,
  59. line_number: int | range | None = None,
  60. contains: str | None = None,
  61. ):
  62. """
  63. Get a DOM element by tag and identifier.
  64. Finds an element by either its line number in the original file or by
  65. matching attribute values. Exactly one match must be found.
  66. Args:
  67. tag: The XML tag name (e.g., "w:del", "w:ins", "w:r")
  68. attrs: Dictionary of attribute name-value pairs to match (e.g., {"w:id": "1"})
  69. line_number: Line number (int) or line range (range) in original XML file (1-indexed)
  70. contains: Text string that must appear in any text node within the element.
  71. Supports both entity notation (&#8220;) and Unicode characters (\u201c).
  72. Returns:
  73. defusedxml.minidom.Element: The matching DOM element
  74. Raises:
  75. ValueError: If node not found or multiple matches found
  76. Example:
  77. elem = editor.get_node(tag="w:r", line_number=519)
  78. elem = editor.get_node(tag="w:r", line_number=range(100, 200))
  79. elem = editor.get_node(tag="w:del", attrs={"w:id": "1"})
  80. elem = editor.get_node(tag="w:p", attrs={"w14:paraId": "12345678"})
  81. elem = editor.get_node(tag="w:commentRangeStart", attrs={"w:id": "0"})
  82. elem = editor.get_node(tag="w:p", contains="specific text")
  83. elem = editor.get_node(tag="w:t", contains="&#8220;Agreement") # Entity notation
  84. elem = editor.get_node(tag="w:t", contains="\u201cAgreement") # Unicode character
  85. """
  86. matches = []
  87. for elem in self.dom.getElementsByTagName(tag):
  88. # Check line_number filter
  89. if line_number is not None:
  90. parse_pos = getattr(elem, "parse_position", (None,))
  91. elem_line = parse_pos[0]
  92. # Handle both single line number and range
  93. if isinstance(line_number, range):
  94. if elem_line not in line_number:
  95. continue
  96. else:
  97. if elem_line != line_number:
  98. continue
  99. # Check attrs filter
  100. if attrs is not None:
  101. if not all(
  102. elem.getAttribute(attr_name) == attr_value
  103. for attr_name, attr_value in attrs.items()
  104. ):
  105. continue
  106. # Check contains filter
  107. if contains is not None:
  108. elem_text = self._get_element_text(elem)
  109. # Normalize the search string: convert HTML entities to Unicode characters
  110. # This allows searching for both "&#8220;Rowan" and ""Rowan"
  111. normalized_contains = html.unescape(contains)
  112. if normalized_contains not in elem_text:
  113. continue
  114. # If all applicable filters passed, this is a match
  115. matches.append(elem)
  116. if not matches:
  117. # Build descriptive error message
  118. filters = []
  119. if line_number is not None:
  120. line_str = (
  121. f"lines {line_number.start}-{line_number.stop - 1}"
  122. if isinstance(line_number, range)
  123. else f"line {line_number}"
  124. )
  125. filters.append(f"at {line_str}")
  126. if attrs is not None:
  127. filters.append(f"with attributes {attrs}")
  128. if contains is not None:
  129. filters.append(f"containing '{contains}'")
  130. filter_desc = " ".join(filters) if filters else ""
  131. base_msg = f"Node not found: <{tag}> {filter_desc}".strip()
  132. # Add helpful hint based on filters used
  133. if contains:
  134. hint = "Text may be split across elements or use different wording."
  135. elif line_number:
  136. hint = "Line numbers may have changed if document was modified."
  137. elif attrs:
  138. hint = "Verify attribute values are correct."
  139. else:
  140. hint = "Try adding filters (attrs, line_number, or contains)."
  141. raise ValueError(f"{base_msg}. {hint}")
  142. if len(matches) > 1:
  143. raise ValueError(
  144. f"Multiple nodes found: <{tag}>. "
  145. f"Add more filters (attrs, line_number, or contains) to narrow the search."
  146. )
  147. return matches[0]
  148. def _get_element_text(self, elem):
  149. """
  150. Recursively extract all text content from an element.
  151. Skips text nodes that contain only whitespace (spaces, tabs, newlines),
  152. which typically represent XML formatting rather than document content.
  153. Args:
  154. elem: defusedxml.minidom.Element to extract text from
  155. Returns:
  156. str: Concatenated text from all non-whitespace text nodes within the element
  157. """
  158. text_parts = []
  159. for node in elem.childNodes:
  160. if node.nodeType == node.TEXT_NODE:
  161. # Skip whitespace-only text nodes (XML formatting)
  162. if node.data.strip():
  163. text_parts.append(node.data)
  164. elif node.nodeType == node.ELEMENT_NODE:
  165. text_parts.append(self._get_element_text(node))
  166. return "".join(text_parts)
  167. def replace_node(self, elem, new_content):
  168. """
  169. Replace a DOM element with new XML content.
  170. Args:
  171. elem: defusedxml.minidom.Element to replace
  172. new_content: String containing XML to replace the node with
  173. Returns:
  174. List[defusedxml.minidom.Node]: All inserted nodes
  175. Example:
  176. new_nodes = editor.replace_node(old_elem, "<w:r><w:t>text</w:t></w:r>")
  177. """
  178. parent = elem.parentNode
  179. nodes = self._parse_fragment(new_content)
  180. for node in nodes:
  181. parent.insertBefore(node, elem)
  182. parent.removeChild(elem)
  183. return nodes
  184. def insert_after(self, elem, xml_content):
  185. """
  186. Insert XML content after a DOM element.
  187. Args:
  188. elem: defusedxml.minidom.Element to insert after
  189. xml_content: String containing XML to insert
  190. Returns:
  191. List[defusedxml.minidom.Node]: All inserted nodes
  192. Example:
  193. new_nodes = editor.insert_after(elem, "<w:r><w:t>text</w:t></w:r>")
  194. """
  195. parent = elem.parentNode
  196. next_sibling = elem.nextSibling
  197. nodes = self._parse_fragment(xml_content)
  198. for node in nodes:
  199. if next_sibling:
  200. parent.insertBefore(node, next_sibling)
  201. else:
  202. parent.appendChild(node)
  203. return nodes
  204. def insert_before(self, elem, xml_content):
  205. """
  206. Insert XML content before a DOM element.
  207. Args:
  208. elem: defusedxml.minidom.Element to insert before
  209. xml_content: String containing XML to insert
  210. Returns:
  211. List[defusedxml.minidom.Node]: All inserted nodes
  212. Example:
  213. new_nodes = editor.insert_before(elem, "<w:r><w:t>text</w:t></w:r>")
  214. """
  215. parent = elem.parentNode
  216. nodes = self._parse_fragment(xml_content)
  217. for node in nodes:
  218. parent.insertBefore(node, elem)
  219. return nodes
  220. def append_to(self, elem, xml_content):
  221. """
  222. Append XML content as a child of a DOM element.
  223. Args:
  224. elem: defusedxml.minidom.Element to append to
  225. xml_content: String containing XML to append
  226. Returns:
  227. List[defusedxml.minidom.Node]: All inserted nodes
  228. Example:
  229. new_nodes = editor.append_to(elem, "<w:r><w:t>text</w:t></w:r>")
  230. """
  231. nodes = self._parse_fragment(xml_content)
  232. for node in nodes:
  233. elem.appendChild(node)
  234. return nodes
  235. def get_next_rid(self):
  236. """Get the next available rId for relationships files."""
  237. max_id = 0
  238. for rel_elem in self.dom.getElementsByTagName("Relationship"):
  239. rel_id = rel_elem.getAttribute("Id")
  240. if rel_id.startswith("rId"):
  241. try:
  242. max_id = max(max_id, int(rel_id[3:]))
  243. except ValueError:
  244. pass
  245. return f"rId{max_id + 1}"
  246. def save(self):
  247. """
  248. Save the edited XML back to the file.
  249. Serializes the DOM tree and writes it back to the original file path,
  250. preserving the original encoding (ascii or utf-8).
  251. """
  252. content = self.dom.toxml(encoding=self.encoding)
  253. self.xml_path.write_bytes(content)
  254. def _parse_fragment(self, xml_content):
  255. """
  256. Parse XML fragment and return list of imported nodes.
  257. Args:
  258. xml_content: String containing XML fragment
  259. Returns:
  260. List of defusedxml.minidom.Node objects imported into this document
  261. Raises:
  262. AssertionError: If fragment contains no element nodes
  263. """
  264. # Extract namespace declarations from the root document element
  265. root_elem = self.dom.documentElement
  266. namespaces = []
  267. if root_elem and root_elem.attributes:
  268. for i in range(root_elem.attributes.length):
  269. attr = root_elem.attributes.item(i)
  270. if attr.name.startswith("xmlns"): # type: ignore
  271. namespaces.append(f'{attr.name}="{attr.value}"') # type: ignore
  272. ns_decl = " ".join(namespaces)
  273. wrapper = f"<root {ns_decl}>{xml_content}</root>"
  274. fragment_doc = defusedxml.minidom.parseString(wrapper)
  275. nodes = [
  276. self.dom.importNode(child, deep=True)
  277. for child in fragment_doc.documentElement.childNodes # type: ignore
  278. ]
  279. elements = [n for n in nodes if n.nodeType == n.ELEMENT_NODE]
  280. assert elements, "Fragment must contain at least one element"
  281. return nodes
  282. def _create_line_tracking_parser():
  283. """
  284. Create a SAX parser that tracks line and column numbers for each element.
  285. Monkey patches the SAX content handler to store the current line and column
  286. position from the underlying expat parser onto each element as a parse_position
  287. attribute (line, column) tuple.
  288. Returns:
  289. defusedxml.sax.xmlreader.XMLReader: Configured SAX parser
  290. """
  291. def set_content_handler(dom_handler):
  292. def startElementNS(name, tagName, attrs):
  293. orig_start_cb(name, tagName, attrs)
  294. cur_elem = dom_handler.elementStack[-1]
  295. cur_elem.parse_position = (
  296. parser._parser.CurrentLineNumber, # type: ignore
  297. parser._parser.CurrentColumnNumber, # type: ignore
  298. )
  299. orig_start_cb = dom_handler.startElementNS
  300. dom_handler.startElementNS = startElementNS
  301. orig_set_content_handler(dom_handler)
  302. parser = defusedxml.sax.make_parser()
  303. orig_set_content_handler = parser.setContentHandler
  304. parser.setContentHandler = set_content_handler # type: ignore
  305. return parser