To check if an XML document is valid using XmlReader, you really need to read the document.
In C #, this will do this:
var txt = "<Viewport thisisbad Left='0' Top='0' Width='1280' Height='720' >"; XmlReader reader = XmlReader.Create(new StringReader(txt)); while (reader.Read()) { }
Result from this code:
Exception: System.Xml.XmlException: 'Left' is an unexpected token. The expected token is '='. Line 1, position 21. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(String expectedToken1, String expectedToken2) at System.Xml.XmlTextReaderImpl.ParseAttributes() at System.Xml.XmlTextReaderImpl.ParseElement() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read()
There is no need to manage the stack of elements, as suggested in another answer . XmlReader does it for you.
You wrote:
When I create an XML reader, it does not cause any errors. Do I have a way to do parsing automatically, like XMLDocument?
The main thing is to understand that XmlReader is an object that reads xml. If you just created it, he has not read xml yet, so of course he cannot tell you if the xml (which he has not read) is valid.
To quickly check the syntax or correct form of XML, call Read () in the XmlReader until it returns null. He will test you. But, understand that once you have done this, XmlReader is at the end of the document. You need to reset to really read and examine the contents of xml. Most of the applications I've seen run simultaneously. In other words, the application checks the contents and delegates a “syntax check”, as you put it, in Reader:
XmlReader reader = XmlReader.Create(sr); while (reader.Read()) // will throw if not well-formed { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: ... break; case XmlNodeType.Element: ... break; case XmlNodeType.Text: ... break; ... } }