2013-04-08 84 views
1

考虑以下SOAP响应:SOAP响应到XML

(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> 

我用肥皂水调用Web服务。

回答

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> 

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

顺便说一句:如果在""之间的代码}{这是行不通的:Title = "notification} 1" 如果您需要帮助这一点,也写评论:)