tags:

views:

303

answers:

4

There are a lot of tutorials that teach on how to validate XML against a schema. But now I want to validate XML syntax only, not against the schema. Meaning I just want to check whether the XML is well-form, that whether there are closing or opening tag that is not done properly.

Is there anyway I can do that in .Net?

+4  A: 

Just open it in an XmlReader and read to the end. If it makes it without throwing an exception, it's well formed.

Joel Coehoorn
A: 

It would probably be a bit easier to use XmlDocument instead.

Steven Sudit
That would work, but it would also try to load the whole thing into memory and create a DOM. Ugh. XmlReader will be _much_ faster.
Joel Coehoorn
Yes, that's entirely true. XmlDocument is EASIER, not faster. My thinking is that, since the goal is to validate the documents, it would be best if the validatOR were unamibiguously correct. Since the process would likely wind up I/O-bound, I don't think the added expense would be a problem unless the files were exceptionally large.
Steven Sudit
+4  A: 

Or if you're on .NET 3.5, you can use XElement.Load().

LINQ to XML's loading functionality is built upon XmlReader. Therefore, you might catch any exceptions that are thrown by the XmlReader.Create overload methods and the XmlReader methods that read and parse the document.

dahlbyk
Use XDocument.Load() if you want to validate the declaration and processing instructions, too.
Joe Chung