XDocument中当前节点的路径
是否可以获取 XDocument 中当前 XElement 的路径?例如,如果我迭代文档中的节点,是否可以通过某种方式获取该节点(XElement)的路径,以便它返回类似 \root\item\child\currentnode 的内容?
Is it possible to get the path of the current XElement in an XDocument? For example, if I'm iterating over the nodes in a document is there some way I can get the path of that node (XElement) so that it returns something like \root\item\child\currentnode ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
萌化2024-11-12 12:02:03
取决于您想要如何使用 XPath。无论哪种情况,您都需要自己沿着树向上走,并在此过程中构建 XPath。
如果你想有可读的字符串用于显示 - 只需加入当前节点的名称(请参阅 BrokenGlass 建议)即可正常工作
如果你想稍后在 XPath 上
- 选择位置 XPath(指定每个节点在其父节点中的位置)是一个选项(类似于 / /[3]/*)。您需要将属性视为特殊情况,因为在具有预定义前缀的属性 XPath 上没有定义顺序
- (前缀的命名空间需要单独存储) - /my:root/my:child[3]/o:prop1/@ t:attr3
- 当您需要半可读且可移植的 XPath 时,使用内联命名空间的 XPath /*[name()='root' & namespace-uri()='http://my.namespace']/....(请参阅名称和命名空间 uri 函数的规范 http://www.w3.org/TR/xpath/#function-namespace-uri)
请注意,注释和处理指令等特殊节点可能需要如果您想要内部节点的 XPath 的真正通用版本,请考虑XML。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
没有内置任何内容,但您可以编写自己的扩展方法:
但这并不能说明元素在其对等组中的位置。
There's nothing built in, but you could write your own extension method:
This doesn't account for the position of the element within its peer group though.