如何访问“行” 和“栏” 解析 XML 时的节点数

发布于 2024-07-14 01:23:00 字数 317 浏览 5 评论 0原文

在 C# 中,当从文件或字符串加载文档时,有没有办法计算出 XmlNode 在原始 XML“文本”中的位置? 我希望能够报告我正在处理的 XML 文档的问题。

例如:

“foo.xml 中的错误 - 属性“pet”的值必须是一种毛茸茸的哺乳动物,位于第 27 行第 13 列 [此处为原始 XML 文本片段...]”

编辑: 无法使用架构验证来完成检查。 这是另一个不那么无聊的示例错误消息来说明:“指定的插件类型‘Addins.LogWindow’必须是公共的”

In C#, is there a way to work out an XmlNode's position in the original XML 'text', when the document is loaded from a file or string? I want to be able to report problems with an XML document that I am processing.

e.g:

"Error in foo.xml - value of attribute 'pet' must be a species of fluffy mammal, at line 27, column 13 [snippet of original XML text here...]"

Edit:
The checks can't be done using schema validation. Here is another, less frivolous sample error message to illustrate: "specified addin type 'Addins.LogWindow' must be public"

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

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

发布评论

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

评论(3

枫林﹌晚霞¤ 2024-07-21 01:23:00

好吧,您不应该编写自己的 XmlParser,但在 Compact Framework 中我们别无选择,因为 XmlDocument 的速度就像达赖喇嘛服用氯胺酮一样慢,因此我们在解析 Xml 文件时使用 XmlReader。

每当我们发现一些混乱或不一致的东西时,我们就会抛出异常,并将 XmlReader 传递给异常。 然后,我们可以通过将 XmlReader 转换为包含行和位置属性的 IXmlLineInfo 对象来提取行位置。

不知道这是否有帮助。 一般来说,我不会在桌面上编写自己的 XmlParser,这就是为什么我不愿建议将此作为解决方案。

Well you're not supposed to write your own XmlParser but in the Compact Framework we have no choice as XmlDocument is as slow as the Dalai Lama on ketamine so we use an XmlReader when parsing an Xml file.

We throw an exception whenever we find something messed up or inconsistent and we pass the XmlReader to the exception. We then can extract the line position by casting the XmlReader into a IXmlLineInfo object which contains properties for the line and position.

Don't know if this will help. Generally I wouldn't be writing my own XmlParser on desktop which is why im reticent to suggest this as a solution.

巴黎夜雨 2024-07-21 01:23:00

抱歉,很少有 DOM 实现能够为您记住 Node 的原始解析位置。 大多数仅报告有关解析错误的任何位置信息。 例如,在 DOM Level 3 LS 中,您只能获得对 DOMLocator 当存在 DOMError

我所知道的唯一在解析后跟踪的小鬼是 pxdom,这是针对 Python 的,所以对你来说没有多大用处。

Sorry, there are very few DOM implementations that will remember the original parsed location of a Node for you. Most only report any position information on a parsing error. For example in DOM Level 3 LS you only get a reference to a DOMLocator when there is a DOMError.

The only imp I know of that keeps track after parsing is pxdom, and that's for Python so not of much use to you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文