考虑以下肥皂反应:
(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},}
如何将此响应转换为:
<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>
我正在使用suds来调用Web服务。
答案 0 :(得分:1)
您是否知道循环中的正则表达式非常强大:
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}>')
结果是:(只是没有格式化)
<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>
无格式:
<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>
我非常喜欢这个。否则我不会创建这个解决方案。 如果你想使用正则表达式替换contextfree语法,你必须要小心。
顺便说一句:如果}
之间的代码中有{
或""
,则无效:Title = "notification} 1"
如果您也需要帮助,请写下评论:)