C#:使用 XmlDocument 解析 XML 时的行信息
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我所知道的唯一其他选项是 XDocument.Load(),其重载接受 LoadOptions.SetLineInfo。它的使用方式与
XmlDocument
大致相同。示例
The only other option I know of is
XDocument.Load()
, whose overloads acceptLoadOptions.SetLineInfo
. This would be consumed in much the same way as anXmlDocument
.Example
(扩展 @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
重载,则需要按如下方式更改代码:现在,您应该能够从以下位置强制转换任何
XmlNode
将此文档传递给PositionXmlElement
以检索行号和列:(Expanding answer from @Andy's comment)
There is no built in way to do this using
XmlDocument
(if you are usingXDocument
, you can use theXDocument.Load()
overload which acceptsLoadOptions.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 anXmlReader
(the otherLoad
overloads will go to the regularXmlDocument
class, which will not give you line number information). If you are currently using theXmlDocument.Load
overload that accepts a filename, you will need to change your code as follows:Now, you should be able to cast any
XmlNode
from this document to aPositionXmlElement
to retrieve line number and column: