日期:2014-05-17  浏览次数:20906 次

用FileStream读取xml文件数据再用XmlDocument载入的问题.
本帖最后由 get333 于 2013-07-16 13:53:19 编辑
为了使程序能够逐次顺序修改配置文件,用FileStream读一个Xml配置文件.代码如下:
FileStream oFs = new System.IO.FileStream("C:\\1.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
FileInfo oFileInfo = new FileInfo("C:\\1.xml");
int intFileLenth = (int)oFileInfo.Length;
byte[] bytes = new byte[intFileLenth];
oFs.Read(bytes, 0, intFileLenth);
string strXml = System.Text.Encoding.Unicode.GetString(bytes);
XmlDocument oDoc3 = new XmlDocument();
oDoc3.LoadXml(strXml);

最后一行,总是报出{"Data at the root level is invalid. Line 1, position 1."}这样的异常。

1.xml 的内容是:
<?xml version="1.0" encoding="utf-16"?>
<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="8570d0c4-78ac-4592-8c49-8dc1fc347ada">
<Document ProjectID="8570d0c4-78ac-4592-8c49-8dc1fc347ada" DocName="报告.doc"><OptUserToken UserID="100" UserName="张三" OptRight="Write" /></Document>
</Project>

请各位诊断下,问题在哪里?

------解决方案--------------------
乱码了?


LoadXml:Data at the root level is invalid. Line 1, position 1.

在使用XmlDocument的LoadXml方法加载xml时,如是提示。意思是第一行第一个字符错误,因为xml要求文件开始必须是<xml这样,所以应该是这地方出了问题。Debug一下,发现了下面的两个问题。

1. 因为是通过web获取xml,所以编码问题导致了xml中出现乱码,我的解决办法是在获取时加入编码格式的设置,根据地址不同使用不同的encoding,具体实现跟使用的download方法有关。

2.在xml文件的开头有隐藏的非法字符,之所以说隐藏,是因为我在debug时快速监视看到的数据完全是正常的(即开始就是类似<xml...),但是取得第一个字符却不是<,而是个双引号。于是在获取到xml后又加了个replace的代码:

rssxml = System.Text.RegularExpressions.Regex.Replace(rssxml, "^[^<]", "");

意思是删除从字符串开始到<之间的所有字符。

解决了上面两个问题,再次运行,通过~