Thursday, May 8, 2008

Sharepoint Webservice Parse Return value

If you are trying to programmatically add items to a sharepoint list, using the web services, you might encounter this error while analysing the return value. I was adding entries to the site directory and on adding an entry, you get a XML result set back. Something similar to what is presented below: ( I have omitted bits which are not relevant )

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<Result ID="2,New"">
<ErrorCode>0x00000000 <ID /">
<z:row ows_ID="20" xmlns:z="#RowsetSchema" /">
</Result">
</Results">

Now, the problem is when you try to parse this, you will encounter the error “Prefix ‘z’ is not defined”. This happens because at this stage, the XML parser does not have any idea what the z in the z:row stands for. The solution I used, was to create a NamespaceManager and add the namespace of z to it manually. The following code will parse the resultset we have.


SiteDirectoryWS.Lists sd = new SiteDirectoryWS.Lists;
...
// form the xml to add an entry in the Sites list.

XmlNode returnNode = sd.UpdateListItems("Sites", insertListElement);

XmlDocument xmlDoc = new XmlDocument;
xmlDoc.LoadXml(returnNode.OuterXml);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("z", "#RowsetSchema");
nsmgr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");

XmlNode elem = returnNode.SelectSingleNode(".//z:row", nsmgr);

If (elem != null)
retID = elem.Attributes("ows_ID").Value;