使用Linq从XML中提取数据

时间:2012-02-17 14:48:51

标签: c# asp.net linq

嗨,我正在努力尝试使用Linq从以下XML中提取数据:

<?xml version='1.0' encoding='utf-8'?>
<ReachResponseEnvelope>
  <BPTResponse>
    <QuotePricing xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns:xsd='http://www.w3.org/2001/XMLSchema' CustomerId='2478'
    CustomerQuoteRefNo='' BPTQuoteRefNo='1185129' Product='NNE'
    ResponseCode='P0001' IsQuickQuote='true'
    xmlns='http://www.infoaxon.com/BPT/Services/Schemas/'>
      <TotalPricing>
        <InstallRevenue>2380</InstallRevenue>
        <RentalRevenue>10620</RentalRevenue>
        <AncillaryCharges>
          <Install>0</Install>
          <Rental>0</Rental>
        </AncillaryCharges>
        <QosCost>
          <Install>0</Install>
          <Rental>0</Rental>
        </QosCost>
        <ReportingCost>
          <Install>0</Install>
          <Rental>0</Rental>
        </ReportingCost>
        <TariffSummary>13000</TariffSummary>
      </TotalPricing>
    </QuotePricing>
  </BPTResponse>
</ReachResponseEnvelope>

我有以下Linq,我可以进入QuotoPricing节点,但很难说出InstallRevenue值。任何帮助都会非常感激!!

var v = from page in requestResponses.Elements("ReachResponseEnvelope").Elements("BPTResponse")
select page;

foreach (var record in v)
{
//Struggling here!!!
}

1 个答案:

答案 0 :(得分:1)

添加XNamespace

 XNamespace ns = "http://www.infoaxon.com/BPT/Services/Schemas/";
 var v = from page in doc.Elements("ReachResponseEnvelope").Elements("BPTResponse")
                    select page;

 foreach (var record in v)
 {
  var installRevenueElement = record.Element(ns+ "QuotePricing").Element(ns+ "TotalPricing").Element(ns + "InstallRevenue");
  Console.WriteLine(installRevenueElement.Value);
 }