Share via


SharePoint: Read XML File from Document Library

Introduction

As we know the implementation of XDocument.Load(string) doesn't support 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 a 401 error.

Applies to

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

Read a file

If you want to read a file using an application from client machine then use below code:

string strFileURL = "http://servername/sites/TestSite/TestLib/Text.xml ";
WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials
using (StreamReader reader = new StreamReader(webClient.OpenRead(strFileURL))
{  
 XDocument Xdoc = XDocument.Parse(reader.ReadToEnd());
}

Issue

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;

COM

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();
}

SOM

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

string site = "http://servername/sites/TestSite";
 
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()
}}