XDocument doc = XDocument.Parse(somestring);
但我怎么验证如果字符串somestring
是一个良好的XML。是Try Catch
做到这一点的唯一方法?
XDocument doc = XDocument.Parse(somestring);
但我怎么验证如果字符串somestring
是一个良好的XML。是Try Catch
做到这一点的唯一方法?
是试着抓住唯一的方法来做到这一点?
没有为XDocument
没有TryParse
方法,所以try-catch
可能是最好的选择。还要考虑根据模式验证您的XML,因为它不仅会检查XML是否格式良好,还会检查约束条件。
您可能会看到:Validation Against XML Schema (XSD) with the XmlValidatingReader
链接已更改 - 已编辑FYI。 – simonalexander2005
@ simonalexander2005,感谢您的编辑 – Habib
如果您只需要检查是否合式的文档,以最快的方式如下:使用的XmlReader:
var isWellFormedXml = true;
try
{
using (var reader = XmlReader.Create(stream)) // can be a mem stream for string validation
{
while (reader.Read()) {}
}
}
catch
{
isWellFormedXml = false;
}
这样,你不这样做为XDocument DOM花费内存。顺便说一句,XDocument.Parse()使用XmlReader处理XML,所以如果需要分析它们,例外情况是相同的。
由于XML文档通常是机器生成的,因此假定其始终保持良好格式。该规则的例外情况通过例外报告:) –