就是今天,做了一個功能,在一個彈出頁面操作幾個表的數據,形成一個臨時DataTable,然後將它轉換爲XML,然後再return到父級頁面
父級頁面,再將XML解析成DataTable再進行相關操作。
噁心隨之而來,再講XML轉換爲DataTable的時候,總是報錯“根級別上的數據無效。 第 1 行,位置 1",但是調試將xmlData參數直接寫的時候,
不出錯!
或許微軟的錯誤提示已經很明確,最前邊的字符有問題,但是我們感覺凡胎肉眼看到的就是<,沒錯啊!
然後百啊百,可能<的前邊還有空格啊回車之類的,至於怎麼就有這個了,不得而知。
那就想辦法吧,找到xmlData的第一個<,然後截取<之後的所有字符串,然後在最前面+<
xmlData = "<" + xmlData.Substring(xmlData.IndexOf('<') + 1);
附完整代碼:
XML轉換DataSet方法
//將xml對象內容字符串轉換爲DataSet
public static DataSet ConvertXMLToDataSet(string xmlData)
{
xmlData = "<" + xmlData.Substring(xmlData.IndexOf('<') + 1);
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet();
stream = new StringReader(xmlData);
//從stream裝載到XmlTextReader
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
return xmlDS;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (reader != null) reader.Close();
}
}
//將DataSet轉換爲xml對象字符串
public static string ConvertDataSetToXML(DataSet xmlDS)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
//從stream裝載到XmlTextReader
writer = new XmlTextWriter(stream, Encoding.UTF8);
//用WriteXml方法寫入文件.
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding();
return utf.GetString(arr).Trim().Replace("\n", "");
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (writer != null) writer.Close();
}
}