如何使用c#检查xml文件是否为空 [英] How to check if xml file is empty or not using c#

查看:65
本文介绍了如何使用c#检查xml文件是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我想检查一下我的 xml 文件是否为空.我正在尝试将一个 xml 数据更新为另一个我正在使用以下代码.现在请告诉我如何检查我的 xml 文件是否有数据这是我用于更新我的 xml 文件的代码

Hello everyone I want to check my xml file if it is empty or not. I am trying to update one xml data to another for this I am using the following code.Now Please tell me how can I check if my xml file has data or not Here is the code I am using for update my xml file

protected void CheckUpdates()
{
    StringReader strReader = new StringReader("..\\xml\\Updatelist.xml");
    XmlReader reader = XmlReader.Create(strReader);
    try
    {
       while (reader.Read())
       {
           var originalXmlDoc = XDocument.Load("..\\xml\\list.xml"); var newXmlDoc = XDocument.Load("..\\xml\\Updatelist.xml");

           foreach (var newElement in newXmlDoc.Element("blocker").Elements("lst"))
           {
               newElement.Value.Trim();
               if (!originalXmlDoc.Element("blocker").Elements("lst")
                       .Any(oldElement => oldElement.Value.Trim().Equals(
                       newElement.Value.Trim(),
                       StringComparison.InvariantCultureIgnoreCase)))
                {
                   originalXmlDoc.Element("blocker").Add(new XElement("lst", newElement.Value));
                }
             }
             originalXmlDoc.Save("..\\xml\\list.xml", SaveOptions.None);

             XmlDocument doc = new XmlDocument();
             doc.Load("..\\xml\\Updatelist.xml");
             doc.DocumentElement.RemoveAll();
             doc.Save("..\\xml\\Updatelist.xml");
          }
       }
    catch (XmlException ex)
    {
       //Catch xml exception
       //in your case: root element is missing
    }
}

我收到此错误

根级别的数据无效.第 1 行,位置 1.

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

请告诉我如何检查我的 Updatelist.xml 是否为空?

Please tell me how can I check if my Updatelist.xml is empty or not?

现在我收到这个错误

推荐答案

两种方法.

首先是读取文件并检查其结构,以查看其中是否有子文件.请记住,属性 ChildNodes 仅返回 XML DOM 特定级别上的子节点.

The first is to read the file and check its structure in order to see if there are any children in it. Keep in mind that the property ChildNodes returns only the children on the specific level of the XML DOM.

XmlDocument xDoc = new XmlDocument();
if (xDoc.ChildNodes.Count == 0) { 
    // It is empty 
}else if (xDoc.ChildNodes.Count == 1) { 
    // There is only one child, probably the declaration node at the beginning
}else if (xDoc.ChildNodes.Count > 1) { 
    // There are more children on the **root level** of the DOM
}

第二种方法是捕获文档加载时抛出的相应XMLException.

The second way would be to catch the respective XMLException thrown when the document is loaded.

try
{
    XmlDocument doc = new XmlDocument();
    doc.Load("test.xml");
}
catch (XmlException exc)
{
    //invalid file
}

希望我有所帮助!

这篇关于如何使用c#检查xml文件是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆