1

考虑以下肥皂响应:

(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 服务。

4

1 回答 1

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>

我非常喜欢这个。否则我不会创建这个解决方案。如果你想对上下文无关语法使用正则表达式替换,你必须小心。

顺便说一句:如果代码中有一个}or {""这将不起作用:Title = "notification} 1" 如果您也需要这方面的帮助,请写评论 :)

于 2013-04-08T17:20:10.657 回答