DataSet和xml相互转换问题

SparkZG 2017-07-04 11:18:57
读取xml文件,并转换成DataSet,随机就将DataSet再转换成XML文档,然后读取刚刚导出的xml文件会报错:根级别上的数据无效。 行 2,位置 1,我看了下转换的xml文档并没有什么问题,然后将出问题位置的 “<” 删掉再加上就没问题了!很奇怪,不知道大家有没有遇到过。。。下面是我的代码:
       /// <summary>
/// 将xml对象内容转换为dataset
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
private DataSet ConvertXMLToDataSet(string xmlData)
{
using (StringReader stream = new StringReader(xmlData))
{
using (XmlTextReader reader = new XmlTextReader(stream))
{
try
{
DataSet xmlDS = new DataSet();
xmlDS.ReadXml(reader);
return xmlDS;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (reader != null)
reader.Close();
}
}
}
}

/// <summary>
/// 将DataSet转换为xml对象字符串
/// </summary>
/// <param name="xmlDS"></param>
/// <returns></returns>

public string ConvertDataSetToXML(DataSet xmlDS)
{
using (MemoryStream stream = new MemoryStream())
{
//从stream装载到XmlTextReader
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode))
{

try
{
//用WriteXml方法写入文件.
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);

UnicodeEncoding utf = new UnicodeEncoding();
return utf.GetString(arr).Trim();
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (writer != null) writer.Close();
}
}
}
}

/// <summary>
/// 将DataSet转换为xml文件
/// </summary>
/// <param name="xmlDS"></param>
/// <param name="xmlFile"></param>

public void ConvertDataSetToXMLFile(DataSet xmlDS,string xmlFile)
{
using (MemoryStream stream = new MemoryStream())
{
//从stream装载到XmlTextReader
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode))
{

try
{
//用WriteXml方法写入文件.
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);

//返回Unicode编码的文本
UnicodeEncoding utf = new UnicodeEncoding();
StreamWriter sw = new StreamWriter(xmlFile);
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sw.WriteLine(utf.GetString(arr).Trim());
sw.Close();

}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (writer != null) writer.Close();
}
}
}
}


用对比工具也显示此处不同
...全文
170 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
exception92 2017-07-04
  • 打赏
  • 举报
回复
根级别上的数据无效。 行 2,位置 1, -》可以确定是格式的问题,但是情况不同,你这种情况没有遇到过。
SparkZG 2017-07-04
  • 打赏
  • 举报
回复
感觉"<"前面还有个字符,但是看不到,删去之后就好了
SparkZG 2017-07-04
  • 打赏
  • 举报
回复
问题出在 Encoding.Unicode 这里,改成用当前操作系统的ANSI编码方式,即Encoding.Default问题就没有了,具体原因还是不太明白。

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧