如何检查xml文档是否为空白或具有值 [英] how to check if xml document is blank or has values

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

问题描述


如何检查xml文档为空或在xml.load(test.xml)之前具有值?
我正在使用以下代码:

Hi
How to check xml document is blank or has values before xml.load(test.xml) ?
Im using the following code :

XmlDocument xml = new XmlDocument();
xml.Load("test.xml");


当xml文档为空时,它将引发以下错误:
"根元素丢失."


感谢


it throws the following error when the xml document is blank :
"Root element is missing."


thanks

推荐答案

首先,让我们正确放置它. 缺少根元素"不是空文档",这是不是XML文档.没有空" XML文档这样的概念.

而不是检测",您需要弄清XML格式不正确的文本如何潜入此文件并解决此问题.

但是,如果存在一种有效的情况,该文本可以是XML或某些随机"文本(甚至是空字符串;但是,如果是空字符串或几乎为空"(某些字符串在string.Trim()之后变为空),请阅读首先将流放在字符串中并与string.Empty进行比较或检查string.IsNullOrEmpty),则您描述的异常(异常,不是错误)足以说明问题.在某些try-catch块中捕获所有XML异常,识别问题并相应地处理此情况.

但是,找到根本原因并确保文件始终包含XML会更好.至于异常,总是应该捕获它们,但是所有它们都应该仅捕获在每个线程的堆栈顶部以及UI的主循环中.

—SA
First, let''s put it correctly. "Root element is missing" is not an "empty document", this is not an XML document. There is no such concept as "empty" XML document.

Instead of "detecting", you need to sort out how a text not well-formed as XML could sneak in this file and address this problem.

However, if there is a valid scenario when the text can be either XML or some "random" text (even empty string; however, if an empty string or "almost empty" (some string which becomes empty after string.Trim()), read the stream in a string first and compare with string.Empty or check string.IsNullOrEmpty), the exception you describe (exception, not error) is a sufficient and valid indication of the problem. Catch all XML exceptions in some try-catch block, identify the problem and process this case accordingly.

But finding a root cause and making sure the file always contains XML would be much better. As to exceptions, they always should be caught, but all of them should be caught only on the top of stack of each thread, and in the main cycle of the UI.

—SA


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

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