Thursday, July 14, 2011

MSCRM – Parsing Business Entity, XPath memo to self

Just wanted to create a short memo to self as I tend to forget that .net/XPath stuff faster than periods of its usage follow :).

So given the following MS CRM Business Entity xml:

   1: <BusinessEntity 
   2:     xsi:type="DynamicEntity" Name="account" 
   3:     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   4:     xmlns="http://schemas.microsoft.com/crm/2006/WebServices">
   5:     <Properties>
   6:         <Property xsi:type="CrmDateTimeProperty" Name="v2_lastchangeon">
   7:             <Value>2011-07-13T10:46:15Z</Value>
   8:         </Property>
   9:     </Properties>
  10: </BusinessEntity>

One can parse it down to the value of v2_lastchangeon property as follows:

   1: XmlDocument xdoc = new XmlDocument();
   2: xdoc.LoadXml(xml);
   3:  
   4: var element = xdoc.DocumentElement;
   5:  
   6: XmlNamespaceManager nsmgr = new XmlNamespaceManager(
   7: OwnerDocument.NameTable);
   8: nsmgr.AddNamespace("x", element.OwnerDocument.DocumentElement.NamespaceURI);
   9: nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
  10:  
  11: var prop = element.SelectSingleNode("x:Properties/x:Property[@Name='v2_lastchangeon']/x:Value/text()", nsmgr);
  12:  
  13: if (prop == null || String.IsNullOrEmpty(prop.Value))
  14: {
  15:     return defaultLastChangeValue;
  16: }

A bit of a catch here for me was (again!!! I’m really a sclerotic!) to use a non empty named namespace (“x” in my case) to get to the result. See http://stackoverflow.com/questions/4271689/xml-selectnodes-with-default-namespace-via-xmlnamespacemanager-not-working-as-exp for more discussion on the subject.

Hope I remember I wrote this when I need it again :):)!

Post a Comment