c# - 确定 xml 文件是否包含数据 - C#

标签 c#

我如何知道我的 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/

相关文章:

c# - 在录制的同时上传视频内容

c# - 如果源字符串不以相同的子字符串开头,则添加一个子字符串

c# - 使用Eigen矩阵库进行C++代码转换

c# - 如何获取 MessageBox 按钮标题?

c# - 为什么 Task.Factory.StartNew() 需要使用 CancellationToken 重载?

c# - 我可以从 C# 转换为 asp.Net 以在线托管应用程序吗?

c# - Visual Studio 2013 和 Update 2(间歇性构建错误)

c# - 如何在 ASP.Net MVC 中使用内连接编写 sql 查询?

c# - 拆分字符串和字符串数组

c# - 当 Lazy<T> 的 .value 属性未锁定时,它如何提供线程安全的延迟加载?