考虑以下肥皂反应:

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

最佳答案

您是否知道循环中的正则表达式可能非常强大:

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>


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

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

10-04 10:28