2016-03-26 50 views
0

我從我的SOAP服務接收到xml,並將其轉換爲字符串並根據模式進行驗證。驗證發生順利,但是當我嘗試將其放到數據集以將其放到我的datagridview中時,它說缺少根元素。下面是我的代碼,xml字符串在對c中的模式進行驗證之後未加載到數據集中

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) 
     { 
      XmlReaderSettings xmlReaderSttngs = new XmlReaderSettings(); 
      XmlDocument xmlDoc = new XmlDocument(); 
      DateTime date = dateTimePicker1.Value; 
      SoapWebReference.SOAPWebService SoapService= new SoapWebReference.SOAPWebService(); 
      string xmlString = SoapService.getSchedule(instructorId, date).OuterXml.ToString(); 

      xmlReaderSttngs.ValidationType = ValidationType.Schema; 
      xmlReaderSttngs.Schemas.Add("","SoapSchema.xsd"); 
      StringReader reader = new StringReader(xmlString); 
      XmlReader xReader; 
      try 
      { 
       xReader = XmlReader.Create(reader, xmlReaderSttngs); 
       xmlDoc.Load(xReader); 
       showSchedule(reader);   
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      }   
     } 

     private void showSchedule(StringReader reader) 
     { 
      DataSet dt = new DataSet(); 
      dt.ReadXml(reader); 
      dataGridView1.DataSource = dt.Tables[0]; 
     } 

令人驚訝的是,當我加載字符串數據集中未經驗證,它加載到數據集,並顯示在GridView。我很困惑,請幫我解決這個問題。

回答

1

您傳遞給showScheduler()StringReader位置已經在最後,因爲它已被用於先前讀取整個字符串。您可以改爲傳遞實際字符串,併爲填充任務創建單獨的StringReaderDataSet

private void showSchedule(string xml) 
{ 
    DataSet dt = new DataSet(); 
    using (var reader = new StringReader(xml)) 
    { 
     dt.ReadXml(reader); 
     dataGridView1.DataSource = dt.Tables[0]; 
    } 
}