0

I'm trying to access the line number of a specific node in an xml document where an error occurs (for example, a misnamed attribute). Here's my code so far for the class that determines the line number of the error:

public class LineNumberFind
{
    private XmlNamespaceManager nsmgr;
    private XmlParserContext context;
    public XmlTextReader reader;

    public LineNumberFind(XmlDocument doc)
    {
        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        doc.WriteTo(tx);
        string str = sw.ToString();
        //nsmgr = new XmlNamespaceManager(new NameTable());
        //context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
        reader = new XmlTextReader(str);
    }

    public int NamingErrorLine(XmlNode node)
    {
        reader.MoveToContent();
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                reader.MoveToAttribute(0);
                if (reader.Value.ToString() == node.Attributes["name"].Value.ToString())
                    return reader.LineNumber;
            }
        }
        return 0;
    }
}

And the code snippet that I'm trying to use the NamingErrorLine method on:

foreach (XmlNode item in doc.SelectNodes("configuration/events/Event"))
        {
            EventEnforce eventNode = new EventEnforce(syntaxError, item);
            if (item.Attributes["name"] != null && item.Attributes["cond"] != null)
            {
                // colorDict returns an int between 0 and 1 with 0 meaning
                // that it is an Action, 1 is a condition, and 2 is Event
                try
                {
                    eventName.Add(item.Attributes["name"].Value);
                    colorDict.Add(item.Attributes["name"].Value, 2);
                    eventDictionary.Add(item.Attributes["cond"].Value, item.Attributes["name"].Value);
                    eventNameToCondDict.Add(item.Attributes["name"].Value, item.Attributes["cond"].Value);
                }
                catch
                {
                    nameingErrors.Add("\tDuplicate entry found. Error at element: <event name=\"" + item.Attributes["name"].Value + "\".../>");
                    MessageBox.Show(lnf.NamingErrorLine(item).ToString());
                    containsSyntaxError = true;
                }
            }

        }

Right now it's telling me that the string I'm using (string str = sw.ToString()) is too long of a string to use in XmlTextReader(string str). Is there a better way of going about this? I've been searching for a while but haven't found anything else.

1 Answers1

0

The XmlTextReader(string) constructor expects a URI, not xml text (see the docs).

Instead consider:

var reader = new XmlTextReader(new StringReader(sw.ToString()));
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152