如何以XML而不是实体的形式访问FetchXML的结果?

时间:2013-09-26 16:21:07

标签: dynamics-crm-2011 fetchxml

过去我的FetchXML以xml格式提供了结果,但是由于我更改了服务器,这个函数string ret = service.Fetch(fetchXml);不再有效,所以我不得不求助于另一个解决方案,但这个给了我更多的工作构建一个XML文件。

获取字符串示例:

 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 个答案:

答案 0 :(得分:1)

过去我使用Serialization将对象转换为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;
            }
        }