xml访问包含
我有一个 xml 结构文件,其排列方式如下:
<AllReport>
<Report>
<DataPoint1>
</DataPoint1>
<DataPoint2>
</DataPoint2>
<DataPoint3>
</DataPoint3>
</Report>
<Report>
<DataPoint1>
</DataPoint1>
<DataPoint2>
</DataPoint2>
<DataPoint3>
</DataPoint3>
</Report>
so on so forth....
</AllReport>
有没有更好的方法可以直接访问 DataPoint1 而不使用多胖 for 循环?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
XPath 表达式
/AllReport/Report/DataPoint1
和//DataPoint1
都将返回示例文档中所有DataPoint1
节点的列表。然后,您可以使用 DOM 库或所选语言提供的任何方式迭代该列表。您使用哪个取决于实际文档的性质。如果您希望访问的每个
DataPoint1
实例都以相同的方式嵌套,则使用前者。如果您无法确定DataPoint1
的嵌套(也许某些报表有子报表,或者AllReport
存在一个“摘要”DataPoint1
子报表,那么出于性能和错误检测的原因,通常最好选择更精确的表达式。
The XPath expressions
/AllReport/Report/DataPoint1
and//DataPoint1
will both return a list of all theDataPoint1
nodes in your sample document. You can then iterate over that list using whatever means your DOM library or chosen language provides you.Which you use would depend on the nature of the actual document. If every instance of
DataPoint1
that you wish to access is nested in the same way, then use the former. If you cannot be sure of the nesting ofDataPoint1
(perhaps some reports have subreports, or there is a "summary"DataPoint1
child ofAllReport
, then the latter may be preferable.It is normally best to choose a more precise expression, both for performance and error-detection reasons.
在 C# 中,您可以使用 LINQ to XML
In C# you can use LINQ to XML