如何通过 Java w3c dom api 获取 xml 元素所在的行号
有没有办法通过 w3c dom api 查找 xml 文件中给定元素所在的行号?
我的用例是我们有 30,000 多个 kml/xml 格式的地图。我编写了一个单元测试,它迭代硬盘驱动器上找到的每个文件(大约 17GB 的大小)并测试它是否可以被我们的应用程序解析。当它失败时,我抛出一个异常,其中包含被视为“无效”的元素实例。为了让我们的绘图部门(这里没有人知道如何编程)能够轻松地追踪拼写错误,我们希望记录导致异常的元素的行号。
有人可以建议一种方法来做到这一点吗?请注意,我们使用的是 Android 1.6 SDK 中包含的 W3C dom api。
Is there a way to lookup the line number that a given element is at in an xml file via the w3c dom api?
My use case for this is that we have 30,000+ maps in kml/xml format. I wrote a unit test that iterates over each file found on the hard drive (about 17GB worth) and tests that it is parseable by our application. When it fails I throw an exception that contains the element instance that was considered "invalid". In order for our mapping department (nobody here knows how to program) to easily track down the typo we would like to log the line number of the element that caused the exception.
Can anybody suggest a way to do this? Please note we are using the W3C dom api included in the Android 1.6 SDK.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可能是错的,但只要 XML 结构本身有效,行号就不应该与您的 XML 解析器/阅读器相关。
您可能会尝试以编程方式推断行号,假设每个节点/内容必须位于不同的行上,但这会很棘手。
I may be wrong, but the line number shouldn't be relevant to your XML parser/reader as long as the XML structure itself is valid.
You might try to extrapolate the line-number programatically on the assumption that each node/content must be on a distinct line but it's going to be tricky.
看起来您正在验证您的 XML 文件。也就是说,您对文档在语法上是否正确(“格式正确”)不感兴趣,而对它们在语义上对您的应用程序是否有效感兴趣。正确的工具是验证 XML 解析器,并结合专用的 XML 方案。例如,请参阅有关 Java 中 XML 验证的教程。验证错误通常包含详细的错误信息,包括有问题元素的行号。
It looks like you're validating your XML files. That is, you're not interested in whether the documents are syntactically correct ("well-formed"), but if they are semantically valid for your application. The right tool for this would be a validating XML parser, coupled with a dedicated XML scheme. See for example this tutorial on XML validation in Java. Validation errors will usually contain detailed error information, including the line number of problematic elements.
我不确定 Android API 是否不同,但普通的 Java 应用程序可能会在 解析 并查看 行号。
I'm not sure whether the Android API is different, but a normal Java application could catch a
SAXParseException
when parsing and look at the line number.