C# 使用linq读取XML文件

C# 使用linq读取XML文件,c#,xml,linq,C#,Xml,Linq,我正在尝试使用LinQ读取一个复杂的XML文件 XML文件有很多级别,如何在一个ILIST中获得所有值。项目中有更多标记。请在此处输入代码 XML具有以下语法: <root> <items> <index_0> <product_id>19</product_id> <menu_rank>2</menu_rank> <menu_country>Guate

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

XML文件有很多级别,如何在一个ILIST中获得所有值。项目中有更多标记。请在此处输入代码

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> 
如何获得“总成本”和“平衡”价值?

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

请提供任何建议

您可以使用以下代码

var costNode=xmlDoc.SelectSingleNode(“/root/total_cost”)

同样地

var balanceNode = xmlDoc.SelectSingleNode("/root/balance")
从这两个XMLElement中,您可以轻松地提取值

因为您已经有了一个
xPath
,所以我建议使用这种方法

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