Jo Le Mi
Jo Le Mi

Reputation: 23

XmlReader and incomplete xml content and EOF

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

Upvotes: 2

Views: 2377

Answers (2)

MaximPG
MaximPG

Reputation: 11

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062875

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.

Upvotes: 4

Related Questions