Sunday, January 10, 2010

Reading xml from a SharePoint server

Every now and then we have to send and receive data through an xml or an RSS feed. Some of these xml files can be kept somewhere at the server or can be kept locally. If the xml is stored at a different location then you have to write a web service that would call it and put a Client access policy there. I had a requirement to read an xml file stored at a sharepoint server. Here is how I have done it without web services.
List<string> itemDetailsList = new List<string>();
 
List<string> itemTitleList = new List<string>();
 
List<string> itemSourceList = new List<string>();
 
private XNamespace z = "#RowsetSchema";
 
public MainPage()
 
{
 
InitializeComponent();
 
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
 
}
 
void MainPage_Loaded(object sender, RoutedEventArgs e)
 
{
 
//this xml path will be kept at a SharePoint server and the uri will have the address of the SharePoint Server.
 
Uri absUrl = new Uri("http://yourSite/_vti_bin/owssvr.dll?Cmd=Display&List=%7BCA37%2D7F%2D408CBF6%2D059D&XMLDATA=TRUE", UriKind.RelativeOrAbsolute);
 
WebClient xmlClient = new WebClient();
 
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
 
xmlClient.DownloadStringAsync(absUrl);
 
}
 

 
void xmlClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 
{
 

 
if (e.Error == null)
 
{
 
XDocument doc = XDocument.Parse(e.Result.ToString());
 
var docNode = from item in doc.Descendants(z + "row")
 
select new
 
{
 
ItemTitle = item.Attribute("ows_NameOrTitle") == null ? string.Empty : item.Attribute("ows_NameOrTitle").Value,
 
ItemDetails = item.Attribute("ows_Details") == null ? string.Empty : item.Attribute("ows_Details").Value,
 
ItemSource = item.Attribute("ows_RequiredField") == null ? string.Empty : item.Attribute("ows_RequiredField").Value
 
};
 
foreach (var itemContent in docNode)
 
{
 
itemTitleList.Add(itemContent.ItemTitle);
 
itemDetailsList.Add(itemContent.ItemDetails);
 
itemSourceList.Add(itemContent.ItemSource);
 
}
 
}
 
else
 
{
 
MessageBox.Show("error while reading from the server");
 
}
 
}

0 comments:

Post a Comment