如何在xml中找到特定节点的行号?

时间:2013-08-01 21:17:47

标签: c# xml numbers line

我正在尝试访问发生错误的xml文档中特定节点的行号(例如,错误命名的属性)。到目前为止,这是我的代码,用于确定错误行号的类:

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;
    }
}

我正在尝试使用NamingErrorLine方法的代码片段:

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;
                }
            }

        }

现在它告诉我我正在使用的字符串(字符串str = sw.ToString())在XmlTextReader(字符串str)中使用的字符串太长。有没有更好的方法来解决这个问题?我一直在寻找,但没有找到任何其他东西。

1 个答案:

答案 0 :(得分:0)

XmlTextReader(string)构造函数需要一个URI,而不是xml文本(参见the docs)。

而是考虑:

var reader = new XmlTextReader(new StringReader(sw.ToString()));