Reputation: 1691
Consider the following soap response:
(ArrayOfNotificationData){NotificationData[] = (NotificationData){Id = 1 Title = "notification 1" Message = "bla bla." Published = 2000-01-01 00:00:00}, (NotificationData){Id = 2 Title = "notification 2" Message = "bla bla." Published = 2000-01-01 00:00:00},}
How can I convert this response to something like:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetNotificationsResponse xmlns="http://localhost/WS.asmx">
<GetNotificationsResult>
<NotificationData>
<Id>1</Id>
<Title>notification 1</Title>
<Message>bla bla.</Message>
<Published>2000-01-01T00:00:00</Published>
</NotificationData>
<NotificationData>
<Id>2</Id>
<Title>notification 1</Title>
<Message>bla bla.</Message>
<Published>2001-01-01T00:00:00</Published>
</NotificationData>
</GetNotificationsResult>
</GetNotificationsResponse>
</soap:Body>
I'm using suds to call the web service.
Upvotes: 1
Views: 492
Reputation: 14853
Did you know that regular expressions in a loop can be very mighty:
import re
s = '''(ArrayOfNotificationData){NotificationData[] = (NotificationData){Id = 1 Title = "notification 1" Message = "bla bla." Published = 2000-01-01 00:00:00}, (NotificationData){Id = 2 Title = "notification 2" Message = "bla bla." Published = 2000-01-01 00:00:00},}'''
def f(d):
for k, v in d.items():
if v is None:
d[k] = ''
return d
def g(reg, rep):
c1 = s
c2 = ''
while c1 != c2:
c2 = c1
c1 = re.sub(reg, lambda m: rep.format(**f(m.groupdict())), c1)
print c1
g('(?P<m>\w+)\s+=\s+(?:(?P<v>\\d+-\\d+-\\d+ \\d+:\\d+:\\d+|\w+)|"(?P<v3>[^"]*)")|(?:(?:\\w|\\[|\\])+\\s*=\\s*)?\\((?P<m2>\w+)\\){(?P<v2>[^}{]*)}\s*,?', '<{m}{m2}>{v}{v2}{v3}</{m}{m2}>')
And the Result is: (just without formatting)
<ArrayOfNotificationData>
<NotificationData>
<Id>1</Id>
<Title>notification 1</Title>
<Message>bla bla.</Message>
<Published>2000-01-01 00:00:00</Published>
</NotificationData>
<NotificationData>
<Id>2</Id>
<Title>notification 2</Title>
<Message>bla bla.</Message>
<Published>2000-01-01 00:00:00</Published>
</NotificationData>
</ArrayOfNotificationData>
Unformatted:
<ArrayOfNotificationData><NotificationData><Id>1</Id> <Title>notification 1</Title> <Message>bla bla.</Message> <Published>2000-01-01 00:00:00</Published></NotificationData> <NotificationData><Id>2</Id> <Title>notification 2</Title> <Message>bla bla.</Message> <Published>2000-01-01 00:00:00</Published></NotificationData></ArrayOfNotificationData>
I like this very much. Otherwise I would not have created this solution. If you want to use regex replacement for contextfree grammars you have to be careful.
Btw: If there is a }
or {
in the code between the ""
this will not work: Title = "notification} 1"
If you need help on this, too, write a comment :)
Upvotes: 1