C#:使用 XmlDocument 解析 XML 时的行信息

发布于 2024-10-31 10:19:18 字数 387 浏览 4 评论 0原文

使用 XmlDocument 解析 XML 文件并且稍后仍保留错误消息的行信息时,我有哪些选项? (顺便说一句,是否可以对 XML 反序列化执行相同的操作?)

选项似乎包括:

What are my options for parsing an XML file with XmlDocument and still retain line information for error messages later on? (as an aside, is it possible to do the same thing with XML Deserialisation?)

Options seem to include:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

书间行客 2024-11-07 10:19:18

我所知道的唯一其他选项是 XDocument.Load(),其重载接受 LoadOptions.SetLineInfo。它的使用方式与 XmlDocument 大致相同。

示例

The only other option I know of is XDocument.Load(), whose overloads accept LoadOptions.SetLineInfo. This would be consumed in much the same way as an XmlDocument.

Example

假情假意假温柔 2024-11-07 10:19:18

(扩展 @Andy 评论的答案)

没有内置方法可以使用 XmlDocument 执行此操作(如果您使用 XDocument,则可以使用 XDocument.Load() 重载它接受 LoadOptions.SetLineInfo - 请参阅此问题) 。

虽然没有内置方法,但您可以从此处使用 PositionXmlDocument 包装类(来自 SharpDevelop 项目):

https://github.com/icsharpcode/WpfDesigner/blob/5a994b0ff55b9e8f5c41c4573a4e970406ed2fcd/WpfDesign.XamlDom/Project/PositionXmlDocument.cs

为了使用它,您需要使用 Load 接受 XmlReader 重载(其他 Load 重载将转到常规 XmlDocument 类,该类不会为您提供行号信息) 。如果您当前正在使用接受文件名的 XmlDocument.Load 重载,则需要按如下方式更改代码:

using (var reader = new XmlTextReader(filename))
{
    var doc = new PositionXmlDocument();
    doc.Load(reader);
}

现在,您应该能够从以下位置强制转换任何 XmlNode将此文档传递给 PositionXmlElement 以检索行号和列:

var node = doc.ChildNodes[1];
var elem = (PositionXmlElement) node;
Console.WriteLine("Line: {0}, Position: {1}", elem.LineNumber, elem.LinePosition);

(Expanding answer from @Andy's comment)

There is no built in way to do this using XmlDocument (if you are using XDocument, you can use the XDocument.Load() overload which accepts LoadOptions.SetLineInfo - see this question).

While there's no built-in way, you can use the PositionXmlDocument wrapper class from here (from the SharpDevelop project):

https://github.com/icsharpcode/WpfDesigner/blob/5a994b0ff55b9e8f5c41c4573a4e970406ed2fcd/WpfDesign.XamlDom/Project/PositionXmlDocument.cs

In order to use it, you will need to use the Load overload that accepts an XmlReader (the other Load overloads will go to the regular XmlDocument class, which will not give you line number information). If you are currently using the XmlDocument.Load overload that accepts a filename, you will need to change your code as follows:

using (var reader = new XmlTextReader(filename))
{
    var doc = new PositionXmlDocument();
    doc.Load(reader);
}

Now, you should be able to cast any XmlNode from this document to a PositionXmlElement to retrieve line number and column:

var node = doc.ChildNodes[1];
var elem = (PositionXmlElement) node;
Console.WriteLine("Line: {0}, Position: {1}", elem.LineNumber, elem.LinePosition);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文