Skip to content

Commit 7b6b076

Browse files
committed
fix(xml_capture): Enhance XML formatting with pretty print option using minidom
1 parent c5f9a7c commit 7b6b076

File tree

1 file changed

+43
-8
lines changed

1 file changed

+43
-8
lines changed

onvif/utils/xml_capture.py

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from zeep import Plugin
44
from lxml import etree
5+
from xml.dom import minidom
56

67

78
class XMLCapturePlugin(Plugin):
@@ -35,12 +36,43 @@ def __init__(self, pretty_print=True):
3536
self.last_operation = None
3637
self.history = [] # Store all requests/responses
3738

39+
def _format_xml(self, element):
40+
"""
41+
Format XML element with proper indentation using minidom.
42+
43+
Args:
44+
element: lxml Element to format
45+
46+
Returns:
47+
str: Pretty-printed XML string
48+
"""
49+
try:
50+
# Convert lxml element to string
51+
xml_string = etree.tostring(element, encoding="unicode")
52+
# Parse with minidom and pretty print
53+
dom = minidom.parseString(xml_string)
54+
# Use toprettyxml with proper indentation
55+
pretty_xml = dom.toprettyxml(indent=" ", encoding=None)
56+
# Remove extra blank lines and XML declaration
57+
lines = [line for line in pretty_xml.split('\n') if line.strip()]
58+
# Remove XML declaration line if present
59+
if lines and lines[0].startswith('<?xml'):
60+
lines = lines[1:]
61+
return '\n'.join(lines)
62+
except Exception as e:
63+
# Fallback to lxml if minidom fails
64+
return etree.tostring(element, pretty_print=True, encoding="unicode")
65+
3866
def egress(self, envelope, http_headers, operation, binding_options):
3967
"""Called before sending the SOAP request"""
40-
# Serialize XML
41-
self.last_sent_xml = etree.tostring(
42-
envelope, pretty_print=self.pretty_print, encoding="unicode"
43-
)
68+
# Serialize XML with proper pretty printing
69+
if self.pretty_print:
70+
self.last_sent_xml = self._format_xml(envelope)
71+
else:
72+
self.last_sent_xml = etree.tostring(
73+
envelope, pretty_print=False, encoding="unicode"
74+
)
75+
4476
self.last_operation = operation.name
4577

4678
# Store in history
@@ -57,10 +89,13 @@ def egress(self, envelope, http_headers, operation, binding_options):
5789

5890
def ingress(self, envelope, http_headers, operation):
5991
"""Called after receiving the SOAP response"""
60-
# Serialize XML
61-
self.last_received_xml = etree.tostring(
62-
envelope, pretty_print=self.pretty_print, encoding="unicode"
63-
)
92+
# Serialize XML with proper pretty printing
93+
if self.pretty_print:
94+
self.last_received_xml = self._format_xml(envelope)
95+
else:
96+
self.last_received_xml = etree.tostring(
97+
envelope, pretty_print=False, encoding="unicode"
98+
)
6499

65100
# Store in history
66101
self.history.append(

0 commit comments

Comments
 (0)