简体   繁体   中英

xml string is not loading to dataset after validating against schema in c#

I recieve a xml from my SOAP service and I convert it to a string and validate against a schema. Validation happens smoothly but when I try to put it to a dataset to put it to my datagridview it says that root element is missing. Below is my code,

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

The surprising thing is that when I load the string to the dataset without validation, it loads to the dataset and shows in the gridview. I'm confused with this, please help me to solve this.

Your StringReader position when it passed to showScheduler() is already at the end, since it has been used to read the entire string previously. You can pass the actual string instead, and create a separate StringReader for the task of populating DataSet :

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

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