2011-03-28 194 views
2

在客戶端的服務器+ GWT上使用.NET c#,我有一個Web窗體,它接受用戶輸入,然後構建一個XML字符串並將其存儲在數據庫中。然後我需要從數據庫中讀取它,通過tcp將它發送到手持設備,並將其解析爲XElement。一切運作良好,直到您從Word中複製和粘貼文本或在這種情況下脫穎而出,當我嘗試這樣做:c#解析包含HTML特殊字符的字符串XElement

XElement.parse(str); 

它拋出一個異常:

'.', hexadecimal value 0x00, is an invalid character. Line 132, position 111. 

例字符,將導致此問題是正確的撇號字符(0x2019)。現在可能會有一大堆特殊字符可能從excel/word複製粘貼等。處理此問題的最佳方法是什麼?下面是我如何構建從流串:

protected CallResult callUsingSocketClass(string methodName, params Action<CallParameters>[] addParameters) 

{ WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_ENTRY_EXIT, 「++調用({0},...)」,方法名);

 if (this.OnTransferring != null) 
     { 
      if (!this.OnTransferring()) 
      { 
       return null; 
      } 
     } 
     CallParameters parameters = new CallParameters(this, methodName); 
     foreach (var addParameter in addParameters) 
     { 
      addParameter(parameters); 
     } 

     string post = this.CreatePost(parameters); 
     WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC(Method={0}, host={1}, port={2}, post='{3}')", methodName, this.Host, this.Port, post); 
     byte[] postBytes = Encoding.UTF8.GetBytes(post); 

     // 
     // Send the request and wait for the reply. 
     // 
     char[] replyContentChars = null; 
     for (int attempts = 0; attempts < 3; attempts++) 
     { 
      Socket socket = null; 
      try 
      { 
       WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC - creating socket for RPC call..."); 
       if (this.OnTransferring != null) 
       { 
        if (!this.OnTransferring()) 
        { 
         return null; 
        } 
       } 
       string hostID = this.Host; 
       if (this.HostIPAddress != null) 
       { 
        hostID = this.HostIPAddress; 
       } 
       using (socket = this.connectToServer(hostID, this.Port)) 
       { 
        if (socket == null) 
        { 
         return null; 
        } 
        if (this.OnTransferring != null) 
        { 
         if (!this.OnTransferring()) 
         { 
          return null; 
         } 
        } 
        WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC - socket created!"); 
        WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC - communicating with server..."); 
        WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC - writing post..."); 
        this.sendDataToServer(socket, postBytes); 
        int replyLength = -1; 
        if (this.OnTransferring != null) 
        { 
         if (!this.OnTransferring()) 
         { 
          return null; 
         } 
        } 
        WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC - reading reply..."); 
        using (var reader = this.receiveStreamFromServer(socket)) 
        { 
         if (this.OnTransferring != null) 
         { 
          if (!this.OnTransferring()) 
          { 
           socket.Close(); 
           socket = null; 
           return null; 
          } 
         } 
         for (; ;) 
         { 
          string lineRaw = reader.ReadLine().Trim(); 
          string line = lineRaw.ToLowerInvariant(); 
          if (line.StartsWith("content-length:")) 
          { 
           replyLength = int.Parse(line.Substring(15)); 
          } 
          else if (line == "") 
          { 
           if (replyLength < 0) 
           { 
            throw new InvalidOperationException("Reply hasn't specified content-length"); 
           } 
           break; 
          } 
          else 
          { 
           if (this.CookieJar != null) 
           { 
            this.CookieJar.ProcessFromServer(lineRaw); 
           } 
          } 
         } 
         // Content starts here 
         replyContentChars = new char[replyLength]; 
         int replyRecv = 0; 
         do 
         { 
          int charsRecv = reader.Read(replyContentChars, replyRecv, replyLength - replyRecv); 
          if (charsRecv <= 0) 
          { 
           break; 
          } 
          replyRecv += charsRecv; 
         } while (replyRecv < replyLength); 
         //int charsRecv = reader.Read(replyContentChars, 0, replyLength); 
         if (replyRecv != replyLength) 
         { 
          untime.Logger.Logger.Error("Web Service call '{0}' received {1} bytes, header indicated {2} bytes", methodName, replyRecv, replyLength); 
          throw new InvalidOperationException(String.Format("Have not received all of reply data - received {0} bytes, expected {1}", replyRecv, replyLength)); 
         } 
        } 
        socket.Close(); 
        socket = null; 
       } 
      } 
      catch (Exception e) 
      { 

       WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC - exception thrown - {0} [{1},{2}]", e.Message, e.Source, e.StackTrace); 
      } 
      finally 
      { 
       if (socket != null) 
       { 
        socket.Close(); 
        socket = null; 
       } 
      } 
      if (replyContentChars != null) 
      { 
       break; 
      } 
      if (this.OnTransferring != null) 
      { 
       if (!this.OnTransferring()) 
       { 
        return null; 
       } 
      } 
     } 
     // 
     // Verify that data has been received. 
     // 
     if (replyContentChars == null) 
     { 
      return null; 
     } 
     if (this.OnTransferring != null) 
     { 
      if (!this.OnTransferring()) 
      { 
       return null; 
      } 
     } 

     // 
     // Process the received data. 
     // 
     string replyContent = new string(replyContentChars); 
     WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL, "RPC(Method={0}, replyContent='{1}')", methodName, replyContent); 

     XElement xReplyContent = XElement.Parse(replyContent); 

     var xReplyBody = xReplyContent.Element(nsSoap + "Body"); 
     var xFault = xReplyBody.Element(nsSoap + "Fault"); 
     if (xFault != null) 
     { 
      // Something has gone wrong on the server 
      var xFaultCode = xFault.Element(nsSoap + "Code"); 
      var xFaultReason = xFault.Element(nsSoap + "Reason"); 
      untime.Logger.Logger.Error("Web Service call to method '{0}' failed: Code='{1}', Reason='{2}'", methodName, (string)xFaultCode, (string)xFaultReason); 
      string faultCode = (string)xFaultCode; 
      var codeParts = faultCode.Split(':'); 
      XmlQualifiedName xmlQualifiedName; 
      if (codeParts.Length == 2) 
      { 
       xmlQualifiedName = new XmlQualifiedName(codeParts[1], codeParts[0]); 
      } 
      else 
      { 
       xmlQualifiedName = new XmlQualifiedName(faultCode); 
      } 
      throw new SoapException((string)xFaultReason, xmlQualifiedName); 
     } 

     var xResponse = xReplyBody.Element(this.nsArgs + (methodName + "Response")); 
     var xResult = xResponse.Element(this.nsArgs + (methodName + "Result")); 
     if (this.OnTransferring != null) 
     { 
      if (!this.OnTransferring()) 
      { 
       return null; 
      } 
     } 
     var result = new CallResult(xResult); 
     return result; 
    } 
+0

代碼不完整。 'replyLength'在哪裏定義?在這個例子中你有一個無盡的'for'循環。 – jgauffin 2011-03-29 10:03:41

+0

好的,我已經粘貼了現在在這裏完成這項工作的方法。從第70行開始,你可以看到我如何建立字符串。 – Shahid 2011-03-29 10:17:21

+0

你從WebServicesClient.Debug.DebugMessage(WebServicesClient.Debug.MASK_RPC_CALL,「RPC(Method = {0},replyContent ='{1}')」,methodName,replyContent)獲得了什麼輸出結果?' – jgauffin 2011-03-29 10:28:29

回答

0

System.Text.Encoding.UTF8因爲它看起來像Excel使用utf。轉換爲您最喜愛的編碼。

+0

試過了......還是有同樣的問題 – Shahid 2011-03-28 15:49:04

+0

你怎麼得到'str'變量? – jgauffin 2011-03-28 16:11:32

+0

字符串實際上被髮送到手持設備。從UTF8中讀取數據流,然後使用UTF8 – Shahid 2011-03-29 08:48:08

0

我已經找到了答案,這裏的問題:

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/54c83f23-e579-48e9-9fbe-bc20232a02fc/

的想法是要麼剝離/從輸入替換Unicode字符或XML使用Unicode編碼構建時:

<?xml version="1.0" encoding="UTF-16"?> 

在上面的帖子中,接受的答案建議使用下面的方法(在此粘貼),但是如果您需要替換某些字符,則需要添加一些代碼來執行此操作:

 public string getRidOfUnprintablesAndUnicode (string inpString) 
    { 
     string outputs = String.Empty; 
     for (int jj = 0; jj < inpString.Length; jj++) 
     { 
      char ch = inpString[ jj ]; 
      if (((int)(byte)ch) >= 32 & ((int)(byte)ch) <= 128) 
      { 
       outputs += ch; 
      } 
     } 
     return outputs; 
    } 
相關問題