Sample code to read XML Data from Web Resource in Plugin in CRM 2011/2013/2015

We recently had a requirement to read xml data stored in a particular web resource in plugin.

Sharing the sample code

public static Dictionary<string, string> GetMarketClusterAndMarketSegment(string webresourceName, string buildingTypeValue, IOrganizationService organizationService)
Dictionary<string, string> dictionaryMarket = new Dictionary<string, string>();

// tk_et_oppline_marketingfilterpicklists
// create request to retrieve Webresource
ColumnSet cols = new ColumnSet();
QueryByAttribute requestWebResource = new QueryByAttribute
EntityName = "webresource",
ColumnSet = cols

Entity webResourceEntity = null;
EntityCollection webResourceEntityCollection = organizationService.RetrieveMultiple(requestWebResource);

if (webResourceEntityCollection.Entities.Count > 0)
webResourceEntity = webResourceEntityCollection.Entities[0];
byte[] binary = Convert.FromBase64String(webResourceEntity.Attributes["content"].ToString());
string resourceContent = System.Text.Encoding.UTF8.GetString(binary);
string byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (resourceContent.StartsWith(byteOrderMarkUtf8))
resourceContent = resourceContent.Remove(0, byteOrderMarkUtf8.Length);

XDocument xmlDocument = XDocument.Parse(resourceContent);

var marketSegment = from t in xmlDocument.Descendants("ParentField").ElementAt(1).Descendants("ShowOption")
where t.Attribute("value").Value.Equals(buildingTypeValue)
select new
marketSegmentValue = t.Parent.Attribute("value").Value,
marketSegmentLabel = t.Parent.Attribute("label").Value

foreach (var v in marketSegment)
dictionaryMarket.Add("marketsegment", v.marketSegmentValue);
var marketCluster = from t in xmlDocument.Descendants("ParentField").ElementAt(0).Descendants("ShowOption")
where t.Attribute("value").Value.Equals(v.marketSegmentValue)
select new
marketClusterValue = t.Parent.Attribute("value").Value,
marketClusterLabel = t.Parent.Attribute("label").Value

foreach (var m in marketCluster)
dictionaryMarket.Add("marketcluster", m.marketClusterValue);

return dictionaryMarket;

Hope it helps..

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

1 thought on “Sample code to read XML Data from Web Resource in Plugin in CRM 2011/2013/2015”

Share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s