我如何知道我的 XML 文件是否包含 namespace 信息以外的数据:
一些文件包含这个:
<?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 文件,因为您只想检查根元素是否丢失。
关于c# - 确定 xml 文件是否包含数据 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1260063/