Read XML file from document library (All Sharepoint version)

Read XML file from document library (All Sharepoint version)

Last week someone asked one question in forum about reading XML file from document library. As we know the implementation of XDocument.Load(string) doesn't supports an authenticated request to retrieve the XML file so we can use the Stream or FileStream to read the file directly, otherwise you will get 401 error.

This code is tested in SP 2010 but should work in other versions as well.

If you want to read a file using an application from client machine then use below code:
WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials
using (StreamReader reader = new StreamReader(webClient.OpenRead(strFileURL))
{                       
   XDocument Xdoc = XDocument.Parse(reader.ReadToEnd());
}


Note: If your XML is a fragment rather than a fully formed XML document then you may expect below error.
Error: There are multiple root elements, line, position .

Workaround: Use XmlDocument class to accept fragment. Ref Link (http://forums.asp.net/t/1234195.aspx)

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(string.Format("<root>{0}</root>",reader.ReadToEnd));
string value = xmlDocument.SelectSingleNode("root/app.Status").InnerText;


If you want to read a file using client object model then use below code:
ClientContext context = new ClientContext("http://servername/sites/TestSite");
context.ExecuteQuery();
Uri testuri = new Uri(strFileURL);
FileInformation info = File.OpenBinaryDirect(context, testuri.AbsolutePath);
using (StreamReader reader = new StreamReader(info.Stream))
{                       
   XDocument Xdoc = XDocument.Parse(reader.ReadToEnd());
   xDoc = xdoc.ToXmlDocument();
}


If you want to read a file using server object model then use below code:

 
using(SPSite spsite = new SPSite(site))
{
 
 using(SPWeb spweb = spsite.OpenWeb())              
 {
    
   SPFile file = spweb.GetFile(strFileURL);
 
   StreamReader reader = new StreamReader(file.OpenBinaryStream());
   XDocument xdoc = XDocument.Parse(reader.ReadToEnd());
   xDoc = xdoc.ToXmlDocument();
   reader.Close()
}}

Hope it could help to other.
Leave a Comment
  • Please add 6 and 7 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Maheshkumar S Tiwari edited Original. Comment: Added code blocks and Tags

Page 1 of 1 (1 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Maheshkumar S Tiwari edited Original. Comment: Added code blocks and Tags

Page 1 of 1 (1 items)