【问题标题】:Reading a XML file using linq使用 linq 读取 XML 文件
【发布时间】:2013-05-25 17:35:47
【问题描述】:

我正在尝试使用 LinQ 读取复杂的 XML 文件。

XML 文件有很多层次,如何在一个 ILIST 中获取所有值。 items中有更多标签。在此处输入代码

XML 具有以下语法:

<root>
  <items>
    <index_0>
      <product_id>19</product_id>
      <menu_rank>2</menu_rank>
      <menu_country>Guatemala</menu_country>
      <menu_country_code>502</menu_country_code>
      <menu_country_abrv>GT</menu_country_abrv>
      <menu_carrier>TIGO</menu_carrier>
      <menu_value>7.0</menu_value>
    </index_0>
    <index_1>
      <product_id>20</product_id>
      <menu_rank>2</menu_rank>
      <menu_country>Guatemala</menu_country>
      <menu_country_code>502</menu_country_code>
      <menu_country_abrv>GT</menu_country_abrv>
      <menu_carrier>TIGO</menu_carrier>
      <menu_value>10.0</menu_value>
    </index_1>
    <index_2>
      <product_id>21</product_id>
      <menu_rank>2</menu_rank>
      <menu_country>Guatemala</menu_country>
      <menu_country_code>502</menu_country_code>
      <menu_country_abrv>GT</menu_country_abrv>
      <menu_carrier>TIGO</menu_carrier>
      <menu_value>14.0</menu_value>
    </index_2>
  </items>
  <d1>2011-09-30 13:00:00</d1>
  <d2>2013-05-24 13:00:00</d2>
  <num_items>4</num_items>
  <total_retail>2.05</total_retail>
  <total_sale>2.05</total_sale>
  <total_cost>1.64</total_cost>
  <total_discount_amount>0.41</total_discount_amount>
  <balance>1.64</balance>
</root> 

我已经尝试过这种方法:

var vrresult = from a in xmlDoc.XPathSelectElements("/root/items/*")
                           select new
                           {                                                              
                               when = a.Element("when").Value,
                               agent_name = a.Element("agent_name").Value,
                               ani = a.Element("ani").Value,
                              product_description = a.Element("product_description").Value,
                               sale = a.Element("sale").Value,
                               cost = a.Element("cost").Value
                           };

如何获得“总成本”和“余额”值?

  <total_sale>2.05</total_sale>
  <total_cost>1.64</total_cost>
  <total_discount_amount>0.41</total_discount_amount>
  <balance>1.64</balance> 

有什么建议

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    你可以使用下面的代码,

    var costNode = xmlDoc.SelectSingleNode("/root/total_cost")

    同样,

    var balanceNode = xmlDoc.SelectSingleNode("/root/balance")
    

    从这两个 XmlElement 中,您可以轻松提取值。

    既然你已经有了xPath,我建议这个方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 2011-03-17
      相关资源
      最近更新 更多