tags:

views:

442

answers:

4

I'm writing a lightweight XML editor, and in cases where the user's input is not well formed, I would like to indicate to the user where the problem is, or at least where the first problem is. Does anyone know of an existing algorithm for this? If looking at code helps, if I could fill in the FindIndexOfInvalidXml method (or something like it), this would answer my question. Thanks!

using System;

namespace TempConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
            int index = FindIndexOfInvalidXml(text);
            Console.WriteLine(index);
        }

        private static int FindIndexOfInvalidXml(string theString)
        {
            int index = -1;

            //Some logic

            return index;
        }
    }
}
+2  A: 

Unless this is an academic exercise, I think that writing your own XML parser is probably not the best way to go about this. I would probably check out the XmlDocument class within the System.Xml namespace and try/catch exceptions for the Load() or LoadXml() methods. The exception's message property should contain info on where the error occurred (row/col numbers) and I suspect it'd be easier to use a regular expression to extract those error messages and the related positional info.

theraccoonbear
+3  A: 

I'd probably just cheat. :) This will get you a line number and position:

string s = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

try
{
    doc.LoadXml(s);
}
catch(System.Xml.XmlException ex)
{
    MessageBox.Show(ex.LineNumber.ToString());
    MessageBox.Show(ex.LinePosition.ToString());
}
Pseudo Masochist
+1  A: 

You should be able to simply load the string into an XmlDocument or an XmlReader and catch XmlException. The XmlException class has a LineNumber property and a LinePosition property.

You can also use XmlValidatingReader if you want to validate against a schema in addition to checking that a document is well-formed.

C. Dragon 76
A: 

You'd want to load the string into an XmlDocument object via the load method and then catch any exceptions.

public bool isValidXml(string xml)
{
    System.Xml.XmlDocument xDoc = null;
    bool valid = false;
    try
    {
        xDoc = new System.Xml.XmlDocument();
        xDoc.loadXml(xmlString);
        valid = true;
    }
    catch
    {
        // trap for errors
    }
    return valid;
}
Jared