【问题标题】:xml access containxml访问包含
【发布时间】:2012-02-13 09:49:29
【问题描述】:

我有一个xml结构文件,其排列方式如下

<AllReport>
    <Report>
            <DataPoint1>
            </DataPoint1>
            <DataPoint2>
            </DataPoint2> 
            <DataPoint3>
            </DataPoint3>     
    </Report>
    <Report>
            <DataPoint1>
            </DataPoint1>
            <DataPoint2>
            </DataPoint2> 
            <DataPoint3>
            </DataPoint3> 
    </Report>
     so on so forth....
</AllReport>

有没有更好的方法直接访问DataPoint1而不使用multi fat for循环?

【问题讨论】:

  • 使用哪种编程语言?

标签: xml data-access-layer


【解决方案1】:

XPath 表达式/AllReport/Report/DataPoint1//DataPoint1 都将返回示例文档中所有DataPoint1 节点的列表。然后,您可以使用您的 DOM 库或选择的语言为您提供的任何方式迭代该列表。

您使用哪个取决于实际文档的性质。如果您希望访问的每个 DataPoint1 实例都以相同的方式嵌套,则使用前者。如果您不能确定DataPoint1 的嵌套(可能有些报表有子报表,或者AllReport 有一个“摘要”DataPoint1 子报表,那么后者可能更可取。

出于性能和错误检测的原因,通常最好选择更精确的表达式。

【讨论】:

    【解决方案2】:

    在 C# 中,您可以使用 LINQ to XML

     var xmlItems = XDocument.Load("yourXML);
     var result = from e in xmlItems.Descendants("Report").Descendants("DataPoint1");
    
    foreach(item in result ){
    
      //it goes though all DataPoint 1
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 2021-05-16
      • 2016-12-20
      • 2015-05-25
      相关资源
      最近更新 更多