2014-10-31 67 views
0

此反序列化XML是字符串:故障在.NET

string incomingOrdreXML = @"<GetOrderStatus xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/OrderStatusConsole""><AccountID>5</AccountID><Batch></Batch><Date></Date><OrderNumber></OrderNumber><Password></Password><Sequence></Sequence><StatusCode></StatusCode><Test></Test><TrackingID></TrackingID></GetOrderStatus>"; 

這是類:

public class GetOrderStatus 
    { 
     public string AccountID { get; set; } 
     public string Password { get; set; } 
     public string Batch { get; set; } 
     public string Sequence { get; set; } 
     public string Test { get; set; } 
     public string Date { get; set; } 
     public string OrderNumber { get; set; } 
     public string StatusCode { get; set; } 
     public string TrackingID { get; set; } 
    } 

這是反串行化代碼:

string incomingOrdreXML = @"<GetOrderStatus xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/OrderStatusConsole""><AccountID>5</AccountID><Batch></Batch><Date></Date><OrderNumber></OrderNumber><Password></Password><Sequence></Sequence><StatusCode></StatusCode><Test></Test><TrackingID></TrackingID></GetOrderStatus>"; 

      var reader = new StringReader(incomingOrdreXML); 
      XmlSerializer serializer = new XmlSerializer(typeof(GetOrderStatus)); 
      var instance = (GetOrderStatus)serializer.Deserialize(reader); 

失敗在最後一行,說

{"<GetOrderStatus xmlns='http://schemas.datacontract.org/2004/07/OrderStatusConsole'> was not expected."} 

這條線將根據誰發送這個XML而改變。這意味着如果發件人是OrderStatusConsole,那麼如果發件人是Jeff,那麼它就像上面那樣,那麼它最終會有Jeff。

任何線索?

在此先感謝。

回答

0

如果你沒有正確的命名空間中定義,或者刪除xmlns='..'線,或使用它不能反序列化:

[XmlRootAttribute(Namespace = 
    "http://schemas.datacontract.org/2004/07/OrderStatusConsole")] 
public class GetOrderStatus 
    { 

     ... 
    } 
0

您可以嘗試實例化XmlSerializer對象是這樣的:

XmlRootAttribute xRoot = new XmlRootAttribute(); 
xRoot.ElementName = "GetOrderStatus"; 
xRoot.Namespace = "http://schemas.datacontract.org/2004/07/OrderStatusConsole"; 

XmlSerializer serializer = new XmlSerializer(typeof(GetOrderStatus), xRoot); 

現在,如果你知道發件人是誰,你可以更改命名空間在實例化串行器之前。

0

你可以看看在xsd工具

xsd myFile.xml /outputdir:myOutputDir 
xsd myFile.xsd /outputdir:myOutputDir /classes 

,這將產生一個XSD或一組XML的一段給定總是可以反序列化爲類。如果您運行多組傳入xml並比較生成的xsds,則應該能夠通過添加任何缺失的元素並在某些minOccurs =「0」或nillable =「true 。