Tuesday, January 22, 2008

handle XmlException raised when XmlDocument.Load(stream)

Keywords: System.XML.XmlDocument class, FileStream




当用一个XmlDocument对象的Load(stream)方法, 去加载一个xml文件时, 有时候会抛出"Root element is missing"这样的XmlException, 很多情况下并不是因为这个Xml文件真的缺少根节点, 或者这个xml不是well formed.


修改的方法是:将FileStream的Position属性设置为0.


if (fileStream.Length>0)


{fileStream.Position=0; //this code is necessary


xmlDocument.Load(fileStream) ;


}

No comments: