我如何知道我的 XML 文件是否还包含名称空间信息之外的数据:
一些文件包含以下内容:
<?xml version="1.0" encoding="UTF-8"?>
如果我遇到这样的文件,我想将该文件放在错误目录中
您可以使用 XmlReader 来避免 XmlDocument 的开销。在您的情况下,您将收到异常,因为根元素丢失。
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
using (StringReader strReader = new StringReader(xml))
{
//You can replace the StringReader object with the path of your xml file.
//In that case, do not forget to remove the "using" lines above.
using (XmlReader reader = XmlReader.Create(strReader))
{
try
{
while (reader.Read())
{
}
}
catch (XmlException ex)
{
//Catch xml exception
//in your case: root element is missing
}
}
}
您可以在检查第一个节点后在 while(reader.Read()) 循环中添加一个条件,以避免读取整个 xml 文件,因为您只想检查根元素是否丢失。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)