C# 如何判断 XML 格式是否正确?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/729001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine if XML is well formed?
提问by PaulB
I've got a large xml document in a string. What's the best way to determine if the xml is well formed?
我在一个字符串中有一个大的 xml 文档。确定 xml 格式是否正确的最佳方法是什么?
采纳答案by Marc Gravell
Something like:
就像是:
static void Main() {
Test("<abc><def/></abc>");
Test("<abc><def/><abc>");
}
static void Test(string xml) {
using (XmlReader xr = XmlReader.Create(
new StringReader(xml))) {
try {
while (xr.Read()) { }
Console.WriteLine("Pass");
} catch (Exception ex) {
Console.WriteLine("Fail: " + ex.Message);
}
}
}
If you need to check against an xsd, then use XmlReaderSettings
.
如果您需要检查 xsd,请使用XmlReaderSettings
.
回答by Brian Agnew
Simply run it through a parser. That will perform the appropriate checks (whether it parses ok).
只需通过解析器运行它。这将执行适当的检查(是否解析正常)。
If it's a large document (as indicated) then an event-based parser (e.g. SAX) will be appropriate since it won't store the document in memory.
如果它是一个大文档(如所示),那么基于事件的解析器(例如 SAX)将是合适的,因为它不会将文档存储在内存中。
It's often useful to have XML utilities around to check this sort of stuff. I use XMLStarlet, which is a command-line set of tools for XML checking/manipulation.
使用 XML 实用程序来检查此类内容通常很有用。我使用XMLStarlet,它是一组用于 XML 检查/操作的命令行工具。
回答by bh213
XmlReader seems a good choice as it should stream the data (not load the whole xml in one go)
XmlReader 似乎是一个不错的选择,因为它应该流式传输数据(而不是一次性加载整个 xml)
回答by dommer
Try using an XmlReaderwith an XmlReaderSettingsthat has ConformanceLevel.Document set.
尝试使用的XmlReader与XmlReaderSettings有ConformanceLevel.Document集。