我正在尝试访问 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;
}
}
}
现在它告诉我,我正在使用的字符串 (string str = sw.ToString()) 太长,无法在 XmlTextReader(string str) 中使用。有没有更好的方法来解决这个问题?我一直在寻找一段时间,但没有找到其他任何东西。