2
votes

I want to implement intellisense in an xml editor using XmlSchemaValidator. The user types "<" and I want to suggest the allowed elements based on an XSD file. For this I need to validate the typed XML content which is of course not complete. Sample:

<element1 atb="1">
    <element2>
        < ==> suggest element3

So the validator needs to validate element1,atb and element2. Then I can use validator.GetExpectedParticles. Since I don't want to parse the content for myself I want to use XmlReader. But the XmlReader isn't able to tell me when he is at EOF (just providing him with the xml-string without the last "<" in the sample).

string s = "<element1 atb='1'><element2>";
StringReader sr = new StringReader(s);
XmlReader xr = XmlReader.Create(sr);
while (!xr.EOF)
{
    xr.Read();
    // ... validate element, attributes ... //
} 

My problem is, that the xr.EOF() never returns true so I can't know when to stop reading and validating. Any Ideas?

Thank you

2
I'm not sure but I think you should treat your XML code like a string. then use parser trees and try to parse that... Why do you want to use XML Classes to validate your XML? - Dr TJ
Mark Gravell is right. Actually, if you try to change <element2> with </element1> in your string, you will see that xr.EOF will become true when you reach the end. That because XmlReader is supposed to work with complete and well-formed Xml's. - digEmAll

2 Answers

4
votes

Editors routinely have to deal with malformed, incomplete, mangled and otherwise borked input. XmlReader is designed to work (only) with valid xml.

In short, that isn't going to work so well. I fully expect you're going to have to either find or write a fault-tolerant parser.

1
votes

XmlReader.Read method will throw XmlException. This exception provides line and position of the error. So you can analyze the rest of file by yourself. XmlReader cannot read invalid XML since it does not know what to expect. You can remove invalid line and try to parse the file again to highlight the rest of file.