2013-10-22 253 views
12

我使用XDocument.Parse成功或失败?

XDocument doc = XDocument.Parse(somestring); 

但我怎么验证如果字符串somestring是一个良好的XML。是Try Catch做到这一点的唯一方法?

+2

由于XML文档通常是机器生成的,因此假定其始终保持良好格式。该规则的例外情况通过例外报告:) –

回答

13

是试着抓住唯一的方法来做到这一点?

没有为XDocument没有TryParse方法,所以try-catch可能是最好的选择。还要考虑根据模式验证您的XML,因为它不仅会检查XML是否格式良好,还会检查约束条件。

您可能会看到:Validation Against XML Schema (XSD) with the XmlValidatingReader

+1

链接已更改 - 已编辑FYI。 – simonalexander2005

+1

@ simonalexander2005,感谢您的编辑 – Habib

5

如果您只需要检查是否合式的文档,以最快的方式如下:使用的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,所以如果需要分析它们,例外情况是相同的。