22
33from zeep import Plugin
44from lxml import etree
5+ from xml .dom import minidom
56
67
78class 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