| 1 |
# vim: set ft=python ts=4 sw=4 expandtab: |
| 2 |
# ruff: file-ignore[non-augmented-assignment] |
| 3 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 4 |
# |
| 5 |
# C E D A R |
| 6 |
# S O L U T I O N S "Software done right." |
| 7 |
# S O F T W A R E |
| 8 |
# |
| 9 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 10 |
# |
| 11 |
# Copyright (c) 2004-2006,2010,2015 Kenneth J. Pronovici. |
| 12 |
# All rights reserved. |
| 13 |
# |
| 14 |
# Portions Copyright (c) 2000 Fourthought Inc, USA. |
| 15 |
# All Rights Reserved. |
| 16 |
# |
| 17 |
# This program is free software; you can redistribute it and/or |
| 18 |
# modify it under the terms of the GNU General Public License, |
| 19 |
# Version 2, as published by the Free Software Foundation. |
| 20 |
# |
| 21 |
# This program is distributed in the hope that it will be useful, |
| 22 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 23 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 24 |
# |
| 25 |
# Copies of the GNU General Public License are available from |
| 26 |
# the Free Software Foundation website, http://www.gnu.org/. |
| 27 |
# |
| 28 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 29 |
# |
| 30 |
# Author : Kenneth J. Pronovici <[email protected]> |
| 31 |
# Language : Python 3 |
| 32 |
# Project : Cedar Backup, release 3 |
| 33 |
# Purpose : Provides general XML-related functionality. |
| 34 |
# |
| 35 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 36 |
|
| 37 |
######################################################################## |
| 38 |
# Module documentation |
| 39 |
######################################################################## |
| 40 |
|
| 41 |
""" |
| 42 |
Provides general XML-related functionality. |
| 43 |
|
| 44 |
What I'm trying to do here is abstract much of the functionality that directly |
| 45 |
accesses the DOM tree. This is not so much to "protect" the other code from |
| 46 |
the DOM, but to standardize the way it's used. It will also help extension |
| 47 |
authors write code that easily looks more like the rest of Cedar Backup. |
| 48 |
|
| 49 |
Module Attributes |
| 50 |
================= |
| 51 |
|
| 52 |
Attributes: |
| 53 |
TRUE_BOOLEAN_VALUES: List of boolean values in XML representing ``True`` |
| 54 |
FALSE_BOOLEAN_VALUES: List of boolean values in XML representing ``False`` |
| 55 |
VALID_BOOLEAN_VALUES: List of valid boolean values in XML |
| 56 |
|
| 57 |
:author: Kenneth J. Pronovici <[email protected]> |
| 58 |
""" |
| 59 |
|
| 60 |
######################################################################## |
| 61 |
# Imported modules |
| 62 |
######################################################################## |
| 63 |
|
| 64 |
import logging |
| 65 |
import re |
| 66 |
import sys |
| 67 |
from io import StringIO |
| 68 |
from xml.dom.minidom import Node, getDOMImplementation, parseString # ruff: ignore[suspicious-xml-minidom-import] # we assume trusted data, so xml.dom is ok |
| 69 |
from xml.parsers.expat import ExpatError |
| 70 |
|
| 71 |
######################################################################## |
| 72 |
# Module-wide constants and variables |
| 73 |
######################################################################## |
| 74 |
|
| 75 |
logger = logging.getLogger("CedarBackup3.log.xml") |
| 76 |
|
| 77 |
TRUE_BOOLEAN_VALUES = ["Y", "y"] |
| 78 |
FALSE_BOOLEAN_VALUES = ["N", "n"] |
| 79 |
VALID_BOOLEAN_VALUES = TRUE_BOOLEAN_VALUES + FALSE_BOOLEAN_VALUES |
| 80 |
|
| 81 |
|
| 82 |
######################################################################## |
| 83 |
# Functions for creating and parsing DOM trees |
| 84 |
######################################################################## |
| 85 |
|
| 86 |
|
| 87 |
def createInputDom(xmlData, name="cb_config"): |
| 88 |
""" |
| 89 |
Creates a DOM tree based on reading an XML string. |
| 90 |
Returns: |
| 91 |
Tuple (xmlDom, parentNode) for the parsed document |
| 92 |
Raises: |
| 93 |
ValueError: If the document can't be parsed |
| 94 |
""" |
| 95 |
try: |
| 96 |
xmlDom = parseString(xmlData) # ruff: ignore[suspicious-xml-mini-dom-usage] # we assume trusted data, so xml.dom is ok |
| 97 |
parentNode = readFirstChild(xmlDom, name) |
| 98 |
return (xmlDom, parentNode) |
| 99 |
except (OSError, ExpatError) as e: |
| 100 |
raise ValueError("Unable to parse XML document: %s" % e) |
| 101 |
|
| 102 |
|
| 103 |
def createOutputDom(name="cb_config"): |
| 104 |
""" |
| 105 |
Creates a DOM tree used for writing an XML document. |
| 106 |
Args: |
| 107 |
name: Base name of the document (root node name) |
| 108 |
Returns: |
| 109 |
Tuple (xmlDom, parentNode) for the new document |
| 110 |
""" |
| 111 |
impl = getDOMImplementation() |
| 112 |
xmlDom = impl.createDocument(None, name, None) |
| 113 |
return (xmlDom, xmlDom.documentElement) |
| 114 |
|
| 115 |
|
| 116 |
######################################################################## |
| 117 |
# Functions for reading values out of XML documents |
| 118 |
######################################################################## |
| 119 |
|
| 120 |
|
| 121 |
def isElement(node): |
| 122 |
""" |
| 123 |
Returns True or False depending on whether the XML node is an element node. |
| 124 |
""" |
| 125 |
return node.nodeType == Node.ELEMENT_NODE |
| 126 |
|
| 127 |
|
| 128 |
def readChildren(parent, name): |
| 129 |
""" |
| 130 |
Returns a list of nodes with a given name immediately beneath the |
| 131 |
parent. |
| 132 |
|
| 133 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 134 |
direct children of the passed-in parent node. |
| 135 |
|
| 136 |
Underneath, we use the Python ``getElementsByTagName`` method, which is |
| 137 |
pretty cool, but which (surprisingly?) returns a list of all children |
| 138 |
with a given name below the parent, at any level. We just prune that |
| 139 |
list to include only children whose ``parentNode`` matches the passed-in |
| 140 |
parent. |
| 141 |
|
| 142 |
Args: |
| 143 |
parent: Parent node to search beneath |
| 144 |
name: Name of nodes to search for |
| 145 |
|
| 146 |
Returns: |
| 147 |
List of child nodes with correct parent, or an empty list if |
| 148 |
no matching nodes are found. |
| 149 |
""" |
| 150 |
lst = [] |
| 151 |
if parent is not None: |
| 152 |
result = parent.getElementsByTagName(name) |
| 153 |
for entry in result: |
| 154 |
if entry.parentNode is parent: |
| 155 |
lst.append(entry) |
| 156 |
return lst |
| 157 |
|
| 158 |
|
| 159 |
def readFirstChild(parent, name): |
| 160 |
""" |
| 161 |
Returns the first child with a given name immediately beneath the parent. |
| 162 |
|
| 163 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 164 |
direct children of the passed-in parent node. |
| 165 |
|
| 166 |
Args: |
| 167 |
parent: Parent node to search beneath |
| 168 |
name: Name of node to search for |
| 169 |
|
| 170 |
Returns: |
| 171 |
First properly-named child of parent, or ``None`` if no matching nodes are found |
| 172 |
""" |
| 173 |
result = readChildren(parent, name) |
| 174 |
if not result: |
| 175 |
return None |
| 176 |
return result[0] |
| 177 |
|
| 178 |
|
| 179 |
def readStringList(parent, name): |
| 180 |
""" |
| 181 |
Returns a list of the string contents associated with nodes with a given |
| 182 |
name immediately beneath the parent. |
| 183 |
|
| 184 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 185 |
direct children of the passed-in parent node. |
| 186 |
|
| 187 |
First, we find all of the nodes using :any:`readChildren`, and then we |
| 188 |
retrieve the "string contents" of each of those nodes. The returned list |
| 189 |
has one entry per matching node. We assume that string contents of a |
| 190 |
given node belong to the first ``TEXT_NODE`` child of that node. Nodes |
| 191 |
which have no ``TEXT_NODE`` children are not represented in the returned |
| 192 |
list. |
| 193 |
|
| 194 |
Args: |
| 195 |
parent: Parent node to search beneath |
| 196 |
name: Name of node to search for |
| 197 |
|
| 198 |
Returns: |
| 199 |
List of strings as described above, or ``None`` if no matching nodes are found |
| 200 |
""" |
| 201 |
lst = [] |
| 202 |
result = readChildren(parent, name) |
| 203 |
for entry in result: |
| 204 |
if entry.hasChildNodes(): |
| 205 |
for child in entry.childNodes: |
| 206 |
if child.nodeType == Node.TEXT_NODE: |
| 207 |
lst.append(child.nodeValue) |
| 208 |
break |
| 209 |
if not lst: |
| 210 |
lst = None |
| 211 |
return lst |
| 212 |
|
| 213 |
|
| 214 |
def readString(parent, name): |
| 215 |
""" |
| 216 |
Returns string contents of the first child with a given name immediately |
| 217 |
beneath the parent. |
| 218 |
|
| 219 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 220 |
direct children of the passed-in parent node. We assume that string |
| 221 |
contents of a given node belong to the first ``TEXT_NODE`` child of that |
| 222 |
node. |
| 223 |
|
| 224 |
Args: |
| 225 |
parent: Parent node to search beneath |
| 226 |
name: Name of node to search for |
| 227 |
|
| 228 |
Returns: |
| 229 |
String contents of node or ``None`` if no matching nodes are found |
| 230 |
""" |
| 231 |
result = readStringList(parent, name) |
| 232 |
if result is None: |
| 233 |
return None |
| 234 |
return result[0] |
| 235 |
|
| 236 |
|
| 237 |
def readInteger(parent, name): |
| 238 |
""" |
| 239 |
Returns integer contents of the first child with a given name immediately |
| 240 |
beneath the parent. |
| 241 |
|
| 242 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 243 |
direct children of the passed-in parent node. |
| 244 |
|
| 245 |
Args: |
| 246 |
parent: Parent node to search beneath |
| 247 |
name: Name of node to search for |
| 248 |
|
| 249 |
Returns: |
| 250 |
Integer contents of node or ``None`` if no matching nodes are found |
| 251 |
Raises: |
| 252 |
ValueError: If the string at the location can't be converted to an integer |
| 253 |
""" |
| 254 |
result = readString(parent, name) |
| 255 |
if result is None: |
| 256 |
return None |
| 257 |
else: |
| 258 |
return int(result) |
| 259 |
|
| 260 |
|
| 261 |
def readLong(parent, name): |
| 262 |
""" |
| 263 |
Returns long integer contents of the first child with a given name immediately |
| 264 |
beneath the parent. |
| 265 |
|
| 266 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 267 |
direct children of the passed-in parent node. |
| 268 |
|
| 269 |
Args: |
| 270 |
parent: Parent node to search beneath |
| 271 |
name: Name of node to search for |
| 272 |
|
| 273 |
Returns: |
| 274 |
Long integer contents of node or ``None`` if no matching nodes are found |
| 275 |
Raises: |
| 276 |
ValueError: If the string at the location can't be converted to an integer |
| 277 |
""" |
| 278 |
result = readString(parent, name) |
| 279 |
if result is None: |
| 280 |
return None |
| 281 |
else: |
| 282 |
return int(result) |
| 283 |
|
| 284 |
|
| 285 |
def readFloat(parent, name): |
| 286 |
""" |
| 287 |
Returns float contents of the first child with a given name immediately |
| 288 |
beneath the parent. |
| 289 |
|
| 290 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 291 |
direct children of the passed-in parent node. |
| 292 |
|
| 293 |
Args: |
| 294 |
parent: Parent node to search beneath |
| 295 |
name: Name of node to search for |
| 296 |
|
| 297 |
Returns: |
| 298 |
Float contents of node or ``None`` if no matching nodes are found |
| 299 |
Raises: |
| 300 |
ValueError: If the string at the location can't be converted to a |
| 301 |
float value. |
| 302 |
""" |
| 303 |
result = readString(parent, name) |
| 304 |
if result is None: |
| 305 |
return None |
| 306 |
else: |
| 307 |
return float(result) |
| 308 |
|
| 309 |
|
| 310 |
def readBoolean(parent, name): |
| 311 |
""" |
| 312 |
Returns boolean contents of the first child with a given name immediately |
| 313 |
beneath the parent. |
| 314 |
|
| 315 |
By "immediately beneath" the parent, we mean from among nodes that are |
| 316 |
direct children of the passed-in parent node. |
| 317 |
|
| 318 |
The string value of the node must be one of the values in :any:`VALID_BOOLEAN_VALUES`. |
| 319 |
|
| 320 |
Args: |
| 321 |
parent: Parent node to search beneath |
| 322 |
name: Name of node to search for |
| 323 |
|
| 324 |
Returns: |
| 325 |
Boolean contents of node or ``None`` if no matching nodes are found |
| 326 |
Raises: |
| 327 |
ValueError: If the string at the location can't be converted to a boolean |
| 328 |
""" |
| 329 |
result = readString(parent, name) |
| 330 |
if result is None: |
| 331 |
return None |
| 332 |
else: |
| 333 |
if result in TRUE_BOOLEAN_VALUES: |
| 334 |
return True |
| 335 |
elif result in FALSE_BOOLEAN_VALUES: |
| 336 |
return False |
| 337 |
else: |
| 338 |
raise ValueError("Boolean values must be one of %s." % VALID_BOOLEAN_VALUES) |
| 339 |
|
| 340 |
|
| 341 |
######################################################################## |
| 342 |
# Functions for writing values into XML documents |
| 343 |
######################################################################## |
| 344 |
|
| 345 |
|
| 346 |
def addContainerNode(xmlDom, parentNode, nodeName): |
| 347 |
""" |
| 348 |
Adds a container node as the next child of a parent node. |
| 349 |
|
| 350 |
Args: |
| 351 |
xmlDom: DOM tree as from ``impl.createDocument()`` |
| 352 |
parentNode: Parent node to create child for |
| 353 |
nodeName: Name of the new container node |
| 354 |
|
| 355 |
Returns: |
| 356 |
Reference to the newly-created node |
| 357 |
""" |
| 358 |
containerNode = xmlDom.createElement(nodeName) |
| 359 |
parentNode.appendChild(containerNode) |
| 360 |
return containerNode |
| 361 |
|
| 362 |
|
| 363 |
def addStringNode(xmlDom, parentNode, nodeName, nodeValue): |
| 364 |
""" |
| 365 |
Adds a text node as the next child of a parent, to contain a string. |
| 366 |
|
| 367 |
If the ``nodeValue`` is None, then the node will be created, but will be |
| 368 |
empty (i.e. will contain no text node child). |
| 369 |
|
| 370 |
Args: |
| 371 |
xmlDom: DOM tree as from ``impl.createDocument()`` |
| 372 |
parentNode: Parent node to create child for |
| 373 |
nodeName: Name of the new container node |
| 374 |
nodeValue: The value to put into the node |
| 375 |
|
| 376 |
Returns: |
| 377 |
Reference to the newly-created node |
| 378 |
""" |
| 379 |
containerNode = addContainerNode(xmlDom, parentNode, nodeName) |
| 380 |
if nodeValue is not None: |
| 381 |
textNode = xmlDom.createTextNode(nodeValue) |
| 382 |
containerNode.appendChild(textNode) |
| 383 |
return containerNode |
| 384 |
|
| 385 |
|
| 386 |
def addIntegerNode(xmlDom, parentNode, nodeName, nodeValue): |
| 387 |
""" |
| 388 |
Adds a text node as the next child of a parent, to contain an integer. |
| 389 |
|
| 390 |
If the ``nodeValue`` is None, then the node will be created, but will be |
| 391 |
empty (i.e. will contain no text node child). |
| 392 |
|
| 393 |
The integer will be converted to a string using "%d". The result will be |
| 394 |
added to the document via :any:`addStringNode`. |
| 395 |
|
| 396 |
Args: |
| 397 |
xmlDom: DOM tree as from ``impl.createDocument()`` |
| 398 |
parentNode: Parent node to create child for |
| 399 |
nodeName: Name of the new container node |
| 400 |
nodeValue: The value to put into the node |
| 401 |
|
| 402 |
Returns: |
| 403 |
Reference to the newly-created node |
| 404 |
""" |
| 405 |
if nodeValue is None: |
| 406 |
return addStringNode(xmlDom, parentNode, nodeName, None) |
| 407 |
else: |
| 408 |
return addStringNode(xmlDom, parentNode, nodeName, "%d" % nodeValue) # %d works for both int and long |
| 409 |
|
| 410 |
|
| 411 |
def addLongNode(xmlDom, parentNode, nodeName, nodeValue): |
| 412 |
""" |
| 413 |
Adds a text node as the next child of a parent, to contain a long integer. |
| 414 |
|
| 415 |
If the ``nodeValue`` is None, then the node will be created, but will be |
| 416 |
empty (i.e. will contain no text node child). |
| 417 |
|
| 418 |
The integer will be converted to a string using "%d". The result will be |
| 419 |
added to the document via :any:`addStringNode`. |
| 420 |
|
| 421 |
Args: |
| 422 |
xmlDom: DOM tree as from ``impl.createDocument()`` |
| 423 |
parentNode: Parent node to create child for |
| 424 |
nodeName: Name of the new container node |
| 425 |
nodeValue: The value to put into the node |
| 426 |
|
| 427 |
Returns: |
| 428 |
Reference to the newly-created node |
| 429 |
""" |
| 430 |
if nodeValue is None: |
| 431 |
return addStringNode(xmlDom, parentNode, nodeName, None) |
| 432 |
else: |
| 433 |
return addStringNode(xmlDom, parentNode, nodeName, "%d" % nodeValue) # %d works for both int and long |
| 434 |
|
| 435 |
|
| 436 |
def addBooleanNode(xmlDom, parentNode, nodeName, nodeValue): |
| 437 |
""" |
| 438 |
Adds a text node as the next child of a parent, to contain a boolean. |
| 439 |
|
| 440 |
If the ``nodeValue`` is None, then the node will be created, but will be |
| 441 |
empty (i.e. will contain no text node child). |
| 442 |
|
| 443 |
Boolean ``True``, or anything else interpreted as ``True`` by Python, will |
| 444 |
be converted to a string "Y". Anything else will be converted to a |
| 445 |
string "N". The result is added to the document via :any:`addStringNode`. |
| 446 |
|
| 447 |
Args: |
| 448 |
xmlDom: DOM tree as from ``impl.createDocument()`` |
| 449 |
parentNode: Parent node to create child for |
| 450 |
nodeName: Name of the new container node |
| 451 |
nodeValue: The value to put into the node |
| 452 |
|
| 453 |
Returns: |
| 454 |
Reference to the newly-created node |
| 455 |
""" |
| 456 |
if nodeValue is None: |
| 457 |
return addStringNode(xmlDom, parentNode, nodeName, None) |
| 458 |
else: |
| 459 |
if nodeValue: |
| 460 |
return addStringNode(xmlDom, parentNode, nodeName, "Y") |
| 461 |
else: |
| 462 |
return addStringNode(xmlDom, parentNode, nodeName, "N") |
| 463 |
|
| 464 |
|
| 465 |
######################################################################## |
| 466 |
# Functions for serializing DOM trees |
| 467 |
######################################################################## |
| 468 |
|
| 469 |
|
| 470 |
def serializeDom(xmlDom, indent=3): |
| 471 |
""" |
| 472 |
Serializes a DOM tree and returns the result in a string. |
| 473 |
Args: |
| 474 |
xmlDom: XML DOM tree to serialize |
| 475 |
indent: Number of spaces to indent, as an integer |
| 476 |
Returns: |
| 477 |
String form of DOM tree, pretty-printed |
| 478 |
""" |
| 479 |
xmlBuffer = StringIO() |
| 480 |
serializer = Serializer(xmlBuffer, "UTF-8", indent=indent) |
| 481 |
serializer.serialize(xmlDom) |
| 482 |
xmlData = xmlBuffer.getvalue() |
| 483 |
xmlBuffer.close() |
| 484 |
return xmlData |
| 485 |
|
| 486 |
|
| 487 |
class Serializer: |
| 488 |
""" |
| 489 |
XML serializer class. |
| 490 |
|
| 491 |
This is a customized serializer that I hacked together based on what I found |
| 492 |
in the PyXML distribution. Basically, around release 2.7.0, the only reason |
| 493 |
I still had around a dependency on PyXML was for the PrettyPrint |
| 494 |
functionality, and that seemed pointless. So, I stripped the PrettyPrint |
| 495 |
code out of PyXML and hacked bits of it off until it did just what I needed |
| 496 |
and no more. |
| 497 |
|
| 498 |
This code started out being called PrintVisitor, but I decided it makes more |
| 499 |
sense just calling it a serializer. I've made nearly all of the methods |
| 500 |
private, and I've added a new high-level serialize() method rather than |
| 501 |
having clients call ``visit()``. |
| 502 |
|
| 503 |
Anyway, as a consequence of my hacking with it, this can't quite be called a |
| 504 |
complete XML serializer any more. I ripped out support for HTML and XHTML, |
| 505 |
and there is also no longer any support for namespaces (which I took out |
| 506 |
because this dragged along a lot of extra code, and Cedar Backup doesn't use |
| 507 |
namespaces). However, everything else should pretty much work as expected. |
| 508 |
|
| 509 |
@copyright: This code, prior to customization, was part of the PyXML |
| 510 |
codebase, and before that was part of the 4DOM suite developed by |
| 511 |
Fourthought, Inc. It its original form, it was Copyright (c) 2000 |
| 512 |
Fourthought Inc, USA; All Rights Reserved. |
| 513 |
""" |
| 514 |
|
| 515 |
def __init__(self, stream=sys.stdout, encoding="UTF-8", indent=3): |
| 516 |
""" |
| 517 |
Initialize a serializer. |
| 518 |
Args: |
| 519 |
stream: Stream to write output to |
| 520 |
encoding: Output encoding |
| 521 |
indent: Number of spaces to indent, as an integer |
| 522 |
""" |
| 523 |
self.stream = stream |
| 524 |
self.encoding = encoding |
| 525 |
self._indent = indent * " " |
| 526 |
self._depth = 0 |
| 527 |
self._inText = 0 |
| 528 |
|
| 529 |
def serialize(self, xmlDom): |
| 530 |
""" |
| 531 |
Serialize the passed-in XML document. |
| 532 |
Args: |
| 533 |
xmlDom: XML DOM tree to serialize |
| 534 |
Raises: |
| 535 |
ValueError: If there's an unknown node type in the document |
| 536 |
""" |
| 537 |
self._visit(xmlDom) |
| 538 |
self.stream.write("\n") |
| 539 |
|
| 540 |
def _write(self, text): |
| 541 |
obj = _encodeText(text, self.encoding) |
| 542 |
self.stream.write(obj) |
| 543 |
|
| 544 |
def _tryIndent(self): |
| 545 |
if not self._inText and self._indent: |
| 546 |
self._write("\n" + self._indent * self._depth) |
| 547 |
|
| 548 |
def _visit(self, node): |
| 549 |
""" |
| 550 |
Raises: |
| 551 |
ValueError: If there's an unknown node type in the document |
| 552 |
""" |
| 553 |
if node.nodeType == Node.ELEMENT_NODE: |
| 554 |
return self._visitElement(node) |
| 555 |
|
| 556 |
elif node.nodeType == Node.ATTRIBUTE_NODE: |
| 557 |
return self._visitAttr(node) |
| 558 |
|
| 559 |
elif node.nodeType == Node.TEXT_NODE: |
| 560 |
return self._visitText(node) |
| 561 |
|
| 562 |
elif node.nodeType == Node.CDATA_SECTION_NODE: |
| 563 |
return self._visitCDATASection(node) |
| 564 |
|
| 565 |
elif node.nodeType == Node.ENTITY_REFERENCE_NODE: |
| 566 |
return self._visitEntityReference(node) |
| 567 |
|
| 568 |
elif node.nodeType == Node.ENTITY_NODE: |
| 569 |
return self._visitEntity(node) |
| 570 |
|
| 571 |
elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: |
| 572 |
return self._visitProcessingInstruction(node) |
| 573 |
|
| 574 |
elif node.nodeType == Node.COMMENT_NODE: |
| 575 |
return self._visitComment(node) |
| 576 |
|
| 577 |
elif node.nodeType == Node.DOCUMENT_NODE: |
| 578 |
return self._visitDocument(node) |
| 579 |
|
| 580 |
elif node.nodeType == Node.DOCUMENT_TYPE_NODE: |
| 581 |
return self._visitDocumentType(node) |
| 582 |
|
| 583 |
elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: |
| 584 |
return self._visitDocumentFragment(node) |
| 585 |
|
| 586 |
elif node.nodeType == Node.NOTATION_NODE: |
| 587 |
return self._visitNotation(node) |
| 588 |
|
| 589 |
# It has a node type, but we don't know how to handle it |
| 590 |
raise ValueError("Unknown node type: %s" % repr(node)) |
| 591 |
|
| 592 |
def _visitNodeList(self, node, exclude=None): |
| 593 |
for curr in node: |
| 594 |
curr is not exclude and self._visit(curr) |
| 595 |
|
| 596 |
def _visitNamedNodeMap(self, node): |
| 597 |
for item in list(node.values()): |
| 598 |
self._visit(item) |
| 599 |
|
| 600 |
def _visitAttr(self, node): |
| 601 |
self._write(" " + node.name) |
| 602 |
value = node.value |
| 603 |
text = _translateCDATA(value, self.encoding) |
| 604 |
text, delimiter = _translateCDATAAttr(text) |
| 605 |
self.stream.write("=%s%s%s" % (delimiter, text, delimiter)) |
| 606 |
|
| 607 |
def _visitProlog(self): |
| 608 |
self._write("<?xml version='1.0' encoding='%s'?>" % (self.encoding or "utf-8")) |
| 609 |
self._inText = 0 |
| 610 |
|
| 611 |
def _visitDocument(self, node): |
| 612 |
self._visitProlog() |
| 613 |
node.doctype and self._visitDocumentType(node.doctype) |
| 614 |
self._visitNodeList(node.childNodes, exclude=node.doctype) |
| 615 |
|
| 616 |
def _visitDocumentFragment(self, node): |
| 617 |
self._visitNodeList(node.childNodes) |
| 618 |
|
| 619 |
def _visitElement(self, node): |
| 620 |
self._tryIndent() |
| 621 |
self._write("<%s" % node.tagName) |
| 622 |
for attr in list(node.attributes.values()): |
| 623 |
self._visitAttr(attr) |
| 624 |
if len(node.childNodes): |
| 625 |
self._write(">") |
| 626 |
self._depth = self._depth + 1 |
| 627 |
self._visitNodeList(node.childNodes) |
| 628 |
self._depth = self._depth - 1 |
| 629 |
not (self._inText) and self._tryIndent() |
| 630 |
self._write("</%s>" % node.tagName) |
| 631 |
else: |
| 632 |
self._write("/>") |
| 633 |
self._inText = 0 |
| 634 |
|
| 635 |
def _visitText(self, node): |
| 636 |
text = node.data |
| 637 |
if self._indent: |
| 638 |
text.strip() |
| 639 |
if text: |
| 640 |
text = _translateCDATA(text, self.encoding) |
| 641 |
self.stream.write(text) |
| 642 |
self._inText = 1 |
| 643 |
|
| 644 |
def _visitDocumentType(self, doctype): |
| 645 |
if not doctype.systemId and not doctype.publicId: |
| 646 |
return |
| 647 |
self._tryIndent() |
| 648 |
self._write("<!DOCTYPE %s" % doctype.name) |
| 649 |
if doctype.systemId and '"' in doctype.systemId: |
| 650 |
system = "'%s'" % doctype.systemId |
| 651 |
else: |
| 652 |
system = '"%s"' % doctype.systemId |
| 653 |
if doctype.publicId and '"' in doctype.publicId: |
| 654 |
# We should probably throw an error |
| 655 |
# Valid characters: <space> | <newline> | <linefeed> | |
| 656 |
# [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] |
| 657 |
public = "'%s'" % doctype.publicId |
| 658 |
else: |
| 659 |
public = '"%s"' % doctype.publicId |
| 660 |
if doctype.publicId and doctype.systemId: |
| 661 |
self._write(" PUBLIC %s %s" % (public, system)) |
| 662 |
elif doctype.systemId: |
| 663 |
self._write(" SYSTEM %s" % system) |
| 664 |
if doctype.entities or doctype.notations: |
| 665 |
self._write(" [") |
| 666 |
self._depth = self._depth + 1 |
| 667 |
self._visitNamedNodeMap(doctype.entities) |
| 668 |
self._visitNamedNodeMap(doctype.notations) |
| 669 |
self._depth = self._depth - 1 |
| 670 |
self._tryIndent() |
| 671 |
self._write("]>") |
| 672 |
else: |
| 673 |
self._write(">") |
| 674 |
self._inText = 0 |
| 675 |
return |
| 676 |
|
| 677 |
def _visitEntity(self, node): |
| 678 |
"""Visited from a NamedNodeMap in DocumentType""" |
| 679 |
self._tryIndent() |
| 680 |
self._write("<!ENTITY %s" % (node.nodeName)) |
| 681 |
node.publicId and self._write(" PUBLIC %s" % node.publicId) |
| 682 |
node.systemId and self._write(" SYSTEM %s" % node.systemId) |
| 683 |
node.notationName and self._write(" NDATA %s" % node.notationName) |
| 684 |
self._write(">") |
| 685 |
|
| 686 |
def _visitNotation(self, node): |
| 687 |
"""Visited from a NamedNodeMap in DocumentType""" |
| 688 |
self._tryIndent() |
| 689 |
self._write("<!NOTATION %s" % node.nodeName) |
| 690 |
node.publicId and self._write(" PUBLIC %s" % node.publicId) |
| 691 |
node.systemId and self._write(" SYSTEM %s" % node.systemId) |
| 692 |
self._write(">") |
| 693 |
|
| 694 |
def _visitCDATASection(self, node): |
| 695 |
self._tryIndent() |
| 696 |
self._write("<![CDATA[%s]]>" % (node.data)) |
| 697 |
self._inText = 0 |
| 698 |
|
| 699 |
def _visitComment(self, node): |
| 700 |
self._tryIndent() |
| 701 |
self._write("<!--%s-->" % (node.data)) |
| 702 |
self._inText = 0 |
| 703 |
|
| 704 |
def _visitEntityReference(self, node): |
| 705 |
self._write("&%s;" % node.nodeName) |
| 706 |
self._inText = 1 |
| 707 |
|
| 708 |
def _visitProcessingInstruction(self, node): |
| 709 |
self._tryIndent() |
| 710 |
self._write("<?%s %s?>" % (node.target, node.data)) |
| 711 |
self._inText = 0 |
| 712 |
|
| 713 |
|
| 714 |
def _encodeText(text, encoding): # ruff: ignore[unused-function-argument] |
| 715 |
"""Safely encodes the passed-in text as a Unicode string, converting bytes to UTF-8 if necessary.""" |
| 716 |
if text is None: |
| 717 |
return text |
| 718 |
try: |
| 719 |
if isinstance(text, bytes): |
| 720 |
text = str(text, "utf-8") |
| 721 |
return text |
| 722 |
except UnicodeError: |
| 723 |
raise ValueError("Path could not be safely encoded as utf-8.") |
| 724 |
|
| 725 |
|
| 726 |
def _translateCDATAAttr(characters): |
| 727 |
""" |
| 728 |
Handles normalization and some intelligence about quoting. |
| 729 |
|
| 730 |
@copyright: This code, prior to customization, was part of the PyXML |
| 731 |
codebase, and before that was part of the 4DOM suite developed by |
| 732 |
Fourthought, Inc. It its original form, it was Copyright (c) 2000 |
| 733 |
Fourthought Inc, USA; All Rights Reserved. |
| 734 |
""" |
| 735 |
if not characters: |
| 736 |
return "", "'" |
| 737 |
if "'" in characters: |
| 738 |
delimiter = '"' |
| 739 |
new_chars = re.sub(r'"', """, characters) |
| 740 |
else: |
| 741 |
delimiter = "'" |
| 742 |
new_chars = re.sub(r"'", "'", characters) |
| 743 |
# FIXME: There's more to normalization |
| 744 |
# Convert attribute new-lines to character entity |
| 745 |
# characters is possibly shorter than new_chars (no entities) |
| 746 |
if "\n" in characters: |
| 747 |
new_chars = re.sub("\n", " ", new_chars) # ruff: ignore[unraw-re-pattern] |
| 748 |
return new_chars, delimiter |
| 749 |
|
| 750 |
|
| 751 |
# Note: Unicode object only for now |
| 752 |
def _translateCDATA(characters, encoding="UTF-8", prev_chars="", markupSafe=0): |
| 753 |
""" |
| 754 |
@copyright: This code, prior to customization, was part of the PyXML |
| 755 |
codebase, and before that was part of the 4DOM suite developed by |
| 756 |
Fourthought, Inc. It its original form, it was Copyright (c) 2000 |
| 757 |
Fourthought Inc, USA; All Rights Reserved. |
| 758 |
""" |
| 759 |
CDATA_CHAR_PATTERN = re.compile(r"[&<]|]]>") |
| 760 |
CHAR_TO_ENTITY = {"&": "&", "<": "<", "]]>": "]]>"} |
| 761 |
ILLEGAL_LOW_CHARS = "[\x01-\x08\x0b-\x0c\x0e-\x1f]" |
| 762 |
ILLEGAL_HIGH_CHARS = "\xef\xbf[\xbe\xbf]" |
| 763 |
XML_ILLEGAL_CHAR_PATTERN = re.compile("%s|%s" % (ILLEGAL_LOW_CHARS, ILLEGAL_HIGH_CHARS)) |
| 764 |
if not characters: |
| 765 |
return "" |
| 766 |
if not markupSafe: |
| 767 |
if CDATA_CHAR_PATTERN.search(characters): |
| 768 |
new_string = CDATA_CHAR_PATTERN.subn(lambda m, d=CHAR_TO_ENTITY: d[m.group()], characters)[0] |
| 769 |
else: |
| 770 |
new_string = characters |
| 771 |
if prev_chars[-2:] == "]]" and characters[0] == ">": |
| 772 |
new_string = ">" + new_string[1:] |
| 773 |
else: |
| 774 |
new_string = characters |
| 775 |
# Note: use decimal char entity rep because some browsers are broken |
| 776 |
# FIXME: This will bomb for high characters. Should, for instance, detect |
| 777 |
# The UTF-8 for 0xFFFE and put out  |
| 778 |
if XML_ILLEGAL_CHAR_PATTERN.search(new_string): |
| 779 |
new_string = XML_ILLEGAL_CHAR_PATTERN.subn(lambda m: "&#%i;" % ord(m.group()), new_string)[0] |
| 780 |
return _encodeText(new_string, encoding) |