Thursday, 3 July 2014

Read XML values in Sharepoint 2010 Using Code

Read XML values in SharePoint Using Code
Open VS 2010create a blank SharePoint Solution: Name it: SPReadXML
Add new itemSelect Module: Name it: xmlmodule
Remove .txt file
Right click on xmlmodule select add new item. Select xml file
Click Add.
Change your xml file code with below code.
Now add new webpart to project. Name it: ReadXml
Open ReadXml.cs.cs file
Replace your existing code with below code.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.IO;
using System.Xml.XPath;
using System.Xml.Linq;
namespace SPReadXML.ReadXml
{
[ToolboxItemAttribute(false)]
public class ReadXml : WebPart
{
protected override void CreateChildControls()
{
Label lblID = new Label();
Label lblDisplayName = new Label();
using (SPSite site = new SPSite("http://SERVER:8888/"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("xmlmodule\\XMLFile1.xml");
StreamReader sr = new StreamReader(file.OpenBinaryStream());
XDocument doc = XDocument.Parse(sr.ReadToEnd());
foreach (XElement element in doc.Descendants("Field"))
{
var attID = element.Attribute("ID");
lblID.Text += attID.Value + ";";
var attDisplayName = element.Attribute("DisplayName");
lblDisplayName.Text += attDisplayName.Value + ";";
}
#region XMlRead
//foreach (XElement xe in doc.Descendants("child"))
//{
// if (xe.Element("grandchild") != null)
// {
// var attr = xe.Element("grandchild").Attribute("id");
// if (attr != null && attr.Value == "3")
// {
// string elementValue = xe.Value;
// }
// }
//}
#endregion
#region Working
// string myxml =
// @"
//
//
// 1
//
//

//
// 1
//
//

//
// ";
// XElement elem = XElement.Parse(myxml);
// XNamespace nsr = "http://rediff.com";
// XNamespace nsy = "http://yahoo.com";
// string t = elem.Element("one").Element(nsr + "oneone").Element(nsy + "id").Value;
// lbl.Text += t.ToString() + ";";
#endregion
}
}
this.Controls.Add(lblID);
this.Controls.Add(lblDisplayName);
}
}
}
Deploy solution; add new Readxml webpart to page. You can view your xml field values in the UI.