首页 > 解决方案 > 在 XML 异常处理期间,如何获取导致异常的 XML 文件中的行号?

问题描述

这个问题听起来可能与 Stack Overflow 中的其他问题相似,但又有所不同。

我正在尝试使用new XmlDocument()&加载 XML 文件LoadXml()。这样做时,有一些 xml 标记不完整或不正确,因此会引发异常。我想列出他们。现在我想要对象的这个行号exception

在此处输入图像描述

我想提取用红色箭头指向的行号(我以为是ex.LineNumber,但事实并非如此)。我可以从中提取ex.Message(用黄色突出显示),但如果它可用(如用红色箭头标记的地方),那么我想弄清楚如何获得该值。还是不可能?

更多说明:此外,如果您查看StackTracethen 您可能会发现那是最后提到的另一个行号(Line 47),但这不是我想要的(如下所示)。

   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
   at System.Xml.XmlTextReaderImpl.ThrowTagMismatch(NodeData startTag)
   at System.Xml.XmlTextReaderImpl.ParseEndElement()
   at System.Xml.XmlTextReaderImpl.ParseElementContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
   at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.LoadXml(String xml)
   at <ProjectName>.Program.EvaluateEpisodeList(String strSeriesHomePageCode) in C:\<Path>\<ProjectName>\Program.cs:line 47

希望这能澄清我的问题。

互联网上大多数类似的问题都是从 中提取行号StackTrace,我没有找到任何可以解决我的问题的东西。

提前致谢。

标签: c#xmlexception

解决方案



编辑:我完全误解了你的问题。这是答案:


捕获一个XmlException 而不是一般异常。然后你可以得到行号e.LineNumber

MSDN 有这样的说法LineNumber(我的重点):

获取指示错误发生位置的行号。行号从 1 开始。

尝试将字符串“<\r\nbar”加载为 XML 会引发 XmlException,并显示以下消息:

System.Xml.XmlException: 'Name cannot begin with the '<' character, 十六进制值 0x3C。第 1 行,位置 2。

显示该行号是从 1 开始的(错误在第一行中发现)。 告诉我更多...

像这样:

try
{
    // Load XML here
} 
catch (XmlException e) // <-----
{
    Console.WriteLine("Line: " + e.LineNumber);
}

更多的

是文档,您可能已经找到它:


推荐阅读