2013-09-26 15 views
1

在過去,我的FetchXML以XML格式將結果發送給我,但由於我更改了服務器此功能string ret = service.Fetch(fetchXml);不再有效,所以我不得不使用另一種解決方案,但是這一個給了我更多工作來構建XML文件。如何作爲XML而不是實體訪問FetchXML的結果?

取字符串例如:

string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> 
     <entity name='account'> 
     <attribute name='name'/> 
     <attribute name='telephone1'/> 
     </entity> 
     </fetch>"; 

     EntityCollection ec = organizationProxy.RetrieveMultiple(new FetchExpression(fetchXml)); 


     XElement rootXml = new XElement("account"); 
     foreach (Entity account in ec.Entities) 
     { 
      if (account.Attributes.Contains("name")) 
      { 
       rootXml.Add(new XElement("name", account.Attributes.Contains("name") ? account["name"] : "")); 
       rootXml.Add(new XElement("telephone1", account.Attributes.Contains("telephone1") ? account["telephone1"] : "")); 
      } 
     } 

     res.XmlContent = rootXml.ToString(); 

所以,我在這裏做的是建立由專人XML字符串,我知道CRM所能提供的結果以XML,我已經googleit(http://social.msdn.microsoft.com/Forums/en-US/af4f0251-7306-4d76-863d-9508d88c1b68/dynamic-crm-2011-fetchxml-results-into-xmltextreader-to-build-an-xml-output),但這給我比我的代碼更多的工作。或者沒有其他解決方案?

回答

1

在過去,我已經使用序列化將對象轉換爲XML並再次返回。

要轉換爲XML

 public static string SerializeAnObject(object _object) 
     { 
      System.Xml.XmlDocument doc = new XmlDocument(); 
      System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(_object.GetType()); 
      System.IO.MemoryStream stream = new System.IO.MemoryStream(); 
      try 
      { 
       serializer.Serialize(stream, _object); 
       stream.Position = 0; 
       doc.Load(stream); 
       return doc.InnerXml; 
      } 
      catch (Exception ex) 
      { 
       throw; 
      } 
      finally 
      { 
       stream.Close(); 
       stream.Dispose(); 
      } 
     } 

要將其轉換回實體集合(或其他物體)

 public static object DeSerializeAnObject(string xmlOfAnObject, Type _objectType) 
     { 
      System.IO.StringReader read = new StringReader(xmlOfAnObject); 
      System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(_objectType); 
      System.Xml.XmlReader reader = new XmlTextReader(read); 
      try 
      { 
       return (object)serializer.Deserialize(reader); 
      } 
      catch (Exception ex) 
      { 
       throw; 
      } 
      finally 
      { 
       read.Close(); 
       read.Dispose(); 
       read = null; 
      } 
     } 
相關問題