简体   繁体   中英

How to convert XElement object into a dataset or datatable?

I'm accessing a SharePoint(2007) list through a service reference of lists.asmx created in my console application. Console application is created in VS2012 and .Net 4.5 framework.

ListsSoapClient proxy1 = new ListsSoapClient();
proxy1.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
proxy1.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;    
string listName = "List_For_Test";
DataSet ds1 = new DataSet();
XElement ndQuery = new XElement("Query", "");
XElement ndViewFields = new XElement("ViewFields", "");
XElement ndQueryOptions = new XElement("QueryOptions", "");
XElement items = proxy1.GetListItems(listName, null, ndQuery, ndViewFields, null, ndQueryOptions, null);
ds1 = XElementToDataSet(items);

I need to convert the XML returned in items XElement to dataset/datatable and pass it to a stored procedure written in SQL Server 2008 R2.

I tried using following code but it gave me error

    XElement setup = (from p in x.Descendants() select p).First();
    foreach (XElement xe in setup.Descendants()) // build your DataTable
    dt.Columns.Add(new DataColumn(xe.Name.ToString(), typeof(string))); 
    // on second iteration gave error that "'{#RowsetSchema}row'" column already existing.

This is the XML stream returned from GetListItems() webservice method call

< listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema" xmlns="http://schemas.microsoft.com/sharepoint/soap/"> < rs:data ItemCount="2"> < z:row ows_ContentTypeId="0x01006B57C3DFF39626458A729755ABF3A370" ows_Title="Item#1" ows_ListID="1.00000000000000" ows_Loan_x0020_Number="1234.00000000000" ows_ID="2" ows_ContentType="Item" ows_Modified="2014-04-01 10:06:38" ows_Created="2014-04-01 10:06:38" ows_Author="7017;#, Khushi" ows_Editor="7017;#, Khushi" ows_owshiddenversion="1" ows_WorkflowVersion="1" ows__UIVersion="512" ows__UIVersionString="1.0" ows_Attachments="0" ows__ModerationStatus="0" ows_LinkTitleNoMenu="Item#1" ows_LinkTitle="Item#1" ows_SelectTitle="2" ows_Order="200.000000000000" ows_GUID="{2832ED2B-A45D-4950-8E0E-EEB3E31199AF}" ows_FileRef="2;# List_For_Test/2_.000" ows_FileDirRef="2;#/List_For_Test" ows_Last_x0020_Modified="2;#2014-04-01 10:06:38" ow s_Created_x0020_Date="2;#2014-04-01 10:06:38" ows_FSObjType="2;#0" ows_PermMask="0x7fffffffffffffff" ows_FileLeafRef="2;#2_.000" ows_UniqueId="2;#{F3336392-74F7-45C2-A175-EF36DA219812}" ows_ProgId="2;#" ows_ScopeId="2;#{E9E1B331-7993-4586-93DC-3690EBEBAD9E}" ows__EditMenuTableStart="2_.000" ows__EditMenuTableEnd="2" ows_LinkFilenameNoMenu="2_.000" ows_LinkFilename="2_.000" ows_ServerUrl="/ List_For_Test/2_.000" ows_EncodedAbsUrl="Lists/List_For_Test/2_.000" ows_BaseName="2_" ows_MetaInfo="2;#" ows__Level="1" ows__IsCurrentVersion="1" />
< z:row ows_ContentTypeId="0x01006B57C3DFF39626458A729755ABF3A370" ows_Title="Item#2" ows_ListID="2.00000000000000" ows_Loan_x0020_Number="5678.00000000000" ows_ID="3" ows_ContentType="Item" ows_Modified="2014-04-01 10:06:53" ows_Created="2014-04-01 10:06:53" ows_Author="7017;#Khushi" ows_Editor="7017;#, Khushi" ows_owshiddenversion="1" ows_WorkflowVersion="1" ows__UIVersion="512" ows__UIVersionString="1.0" ows_Attachments="0" ows__ModerationStatus="0" ows_LinkTitleNoMenu="Item#2" ows_LinkTitle="Item#2" ows_SelectTitle="3" ows_Order="300.000000000000" ows_GUID="{8A6C6A66-A795-4054-B793-789B739EA881}" ows_FileRef="3;# /List_For_Test/3_.000" ows_FileDirRef="3;# /List_For_Test" ows_Last_x0020_Modified="3;#2014-04-01 10:06:53" ows_Created_x0020_Date="3;#2014-04-01 10:06:53" ows_FSObjType="3;#0" ows_PermMask="0x7fffffffffffffff" ows_FileLeafRef="3;#3_.000" ows_UniqueId="3;#{434E5737-5591-4A02-91E5-B2C7A2EFF2B3}" ows_ProgId="3;#" ows_ScopeId="3;#{E9E1B331-7993-4586-93DC-3690EBEBAD9E}" ows__E ditMenuTableStart="3_.000" ows__EditMenuTableEnd="3" ows_LinkFilenameNoMenu="3_.000" ows_LinkFilename="3_.000" ows_ServerUrl="/List_For_Test/3_.000" ows_EncodedAbsUrl="Lists/List_For_Test/3_.000" ows_BaseName="3_" ows_MetaInfo="3;#" ows__Level="1" ows__IsCurrentVersion="1" />
< /rs:data> < /listitems>

Please check it here...

public static class XElementExtensions {
public static DataTable ToDataTable(this XElement element) {
    DataSet ds = new DataSet();
    string rawXml = element.ToString();
    ds.ReadXml(new StringReader(rawXml));
    return ds.Tables[0];
}

public static DataTable ToDataTable(this IEnumerable<XElement> elements) {
    return ToDataTable(new XElement("Root", elements));
}
}

Use it like this:

protected void Page_Load(object sender, EventArgs e) {
string xmlFile = Server.MapPath("~/Data.xml");
XDocument document = XDocument.Load(xmlFile);
var booksQuery = from b in document.Elements("NewDataSet").Elements("Table")
                  select b;

DataTable table = booksQuery.ToDataTable();
GridView1.DataSource = table;
GridView1.DataBind();

}

khushi,check this may be useful to you....

public static DataSet XElementToDataSet(XElement xeRecordsList)
{
  DataTable dtRecordsList = new DataTable();

  XElement setup = (from p in xeRecordsList.Descendants() select p).First();
  // builds DataTable
 foreach (XElement xe in setup.Descendants())
 dtRecordsList.Columns.Add(new DataColumn(xe.Name.ToString(), typeof(string)));
 // add columns to your dt

var all = from p in xeRecordsList.Descendants(setup.Name.ToString()) select p;
foreach (XElement xe in all)
{
 DataRow dr = dtRecordsList.NewRow();

 //adding the values
 foreach (XElement xe2 in xe.Descendants())
 {
   bool boolColExists = false;
   //Check for column exists in datatable
   foreach (DataColumn col in dtRecordsList.Columns) 
   {
      if (col.ColumnName == xe2.Name.ToString())
      {
        boolColExists = true;
        break;
      }
   }
  if (boolColExists)
  dr[xe2.Name.ToString()] = xe2.Value;
 }
 dtRecordsList.Rows.Add(dr);
}
DataSet dstRecordsList = new DataSet("RECORDLIST");
dstRecordsList.Tables.Add(dtRecordsList);
dstRecordsList.Tables[0].TableName = "RECORD";
return dstRecordsList;
}

some references: http://www.dotnetpickles.com/2014/02/aspnet-convert-xml-to-datatable-in-cnet.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM