2013-04-08 118 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" 如果您需要幫助這一點,也寫評論:)