如何将XElement对象转换为数据集或数据表?

时间:2014-04-02 16:14:44

标签: c# linq-to-xml sharepoint-2007 xelement

我通过在控制台应用程序中创建的lists.asmx的服务引用访问SharePoint(2007)列表。控制台应用程序在VS2012和.Net 4.5框架中创建。

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

我需要将项目XElement中返回的XML转换为dataset / datatable,并将其传递给用SQL Server 2008 R2编写的存储过程。

我尝试使用以下代码,但它给了我错误

    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.

这是从GetListItems()webservice方法调用

返回的XML流
  

< 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/” &GT; < RS:数据   ItemCount中= “2” &GT; < Z:行   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”   ows_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”/&gt;

  < 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__EditMenuTableStart =“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”/&gt;

  < / RS:数据&GT; < /时listItems&GT;

2 个答案:

答案 0 :(得分:1)

请检查here...

class App extends Component {
  constructor() {
    super();
     this.state = {
        checkids:{
          'cfc0': false,
          'cfc1': false, 
          'cfc2': false,
          'cfc3': false
        }
     };
  }

  handleCheck(e) {
     const checkids = {...this.state.checkids};
     checkids[e.target.id] = e.target.id === "cfc1" ? false : !checkids[e.target.id];

     this.setState({checkids});
  }

  getElements() {
     let arr = [];
     Object.keys(this.state.checkids).forEach(function(element, index) {
        arr.push(
          <Checkbox
             key={index}
             id={element}
             checked={this.state.checkids[element]}
             onCheck={this.handleCheck.bind(this)}
          />
        );
     }, this)
     return arr;
  }

  render() {
    return (
      <MuiThemeProvider>
        <div>
          {this.getElements()}
       </div>
      </MuiThemeProvider>
    );
  }
}

像这样使用:

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

}

答案 1 :(得分:0)

khushi,检查这可能对你有用....

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

一些参考文献: http://www.dotnetpickles.com/2014/02/aspnet-convert-xml-to-datatable-in-cnet.html