且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查xml文档是否为空白或具有值

更新时间:2023-11-25 16:25:28

首先,让我们正确放置它. 缺少根元素"不是空文档",这是不是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