如何使用XDocument从xml响应读取值?

时间:2019-03-26 16:43:17

标签: c# linq-to-xml

尝试从xml响应中获取值时发生错误。错误在下面列出。

  

错误:对象引用未设置为对象的实例。

当代码到达代码行“ var totalCost ...”时发生此错误

响应xml文件:

<RateReply xmlns="http://fedex.com/ws/rate/v24">
  <HighestSeverity>NOTE</HighestSeverity>
  <Notifications>
    <Severity>NOTE</Severity>
    <Source>crs</Source>
    <Code>819</Code>
    <Message>The origin state/province code has been changed.  </Message>
    <LocalizedMessage>The origin state/province code has been changed.  </LocalizedMessage>
  </Notifications>
  <Notifications>
    <Severity>NOTE</Severity>
    <Source>crs</Source>
    <Code>820</Code>
    <Message>The destination state/province code has been changed.  </Message>
    <LocalizedMessage>The destination state/province code has been changed.  </LocalizedMessage>
  </Notifications>
  <Version>
    <ServiceId>crs</ServiceId>
    <Major>24</Major>
    <Intermediate>0</Intermediate>
    <Minor>0</Minor>
  </Version>
  <RateReplyDetails>
    <ServiceType>FEDEX_GROUND</ServiceType>
    <ServiceDescription>
      <ServiceType>FEDEX_GROUND</ServiceType>
      <Code>92</Code>
      <Description>FedEx Ground</Description>
      <AstraDescription>FXG</AstraDescription>
    </ServiceDescription>
    <PackagingType>YOUR_PACKAGING</PackagingType>
    <CommitDetails>
      <ServiceType>FEDEX_GROUND</ServiceType>
      <ServiceDescription>
        <ServiceType>FEDEX_GROUND</ServiceType>
        <Code>92</Code>
        <Description>FedEx Ground</Description>
        <AstraDescription>FXG</AstraDescription>
      </ServiceDescription>
      <DerivedOriginDetail>
        <CountryCode>US</CountryCode>
        <StateOrProvinceCode>FL</StateOrProvinceCode>
        <PostalCode>32809</PostalCode>
        <LocationNumber>327</LocationNumber>
      </DerivedOriginDetail>
      <DerivedDestinationDetail>
        <CountryCode>US</CountryCode>
        <StateOrProvinceCode>NY</StateOrProvinceCode>
        <PostalCode>12302</PostalCode>
        <LocationNumber>122</LocationNumber>
        <AirportId>ALB</AirportId>
      </DerivedDestinationDetail>
      <TransitTime>FOUR_DAYS</TransitTime>
      <BrokerToDestinationDays>0</BrokerToDestinationDays>
    </CommitDetails>
    <DestinationAirportId>ALB</DestinationAirportId>
    <IneligibleForMoneyBackGuarantee>false</IneligibleForMoneyBackGuarantee>
    <TransitTime>FOUR_DAYS</TransitTime>
    <SignatureOption>SERVICE_DEFAULT</SignatureOption>
    <ActualRateType>PAYOR_ACCOUNT_PACKAGE</ActualRateType>
    <RatedShipmentDetails>
      <ShipmentRateDetail>
        <RateType>PAYOR_ACCOUNT_PACKAGE</RateType>
        <RateZone>6</RateZone>
        <RatedWeightMethod>ACTUAL</RatedWeightMethod>
        <DimDivisor>0</DimDivisor>
        <FuelSurchargePercent>7.0</FuelSurchargePercent>
        <TotalBillingWeight>
          <Units>LB</Units>
          <Value>25.0</Value>
        </TotalBillingWeight>
        <TotalBaseCharge>
          <Currency>USD</Currency>
          <Amount>24.17</Amount>
        </TotalBaseCharge>
        <TotalFreightDiscounts>
          <Currency>USD</Currency>
          <Amount>0.0</Amount>
        </TotalFreightDiscounts>
        <TotalNetFreight>
          <Currency>USD</Currency>
          <Amount>24.17</Amount>
        </TotalNetFreight>
        <TotalSurcharges>
          <Currency>USD</Currency>
          <Amount>1.69</Amount>
        </TotalSurcharges>
        <TotalNetFedExCharge>
          <Currency>USD</Currency>
          <Amount>25.86</Amount>
        </TotalNetFedExCharge>
        <TotalTaxes>
          <Currency>USD</Currency>
          <Amount>0.0</Amount>
        </TotalTaxes>
        <TotalNetCharge>
          <Currency>USD</Currency>
          <Amount>25.86</Amount>
        </TotalNetCharge>
        <TotalRebates>
          <Currency>USD</Currency>
          <Amount>0.0</Amount>
        </TotalRebates>
        <TotalDutiesAndTaxes>
          <Currency>USD</Currency>
          <Amount>0.0</Amount>
        </TotalDutiesAndTaxes>
        <TotalAncillaryFeesAndTaxes>
          <Currency>USD</Currency>
          <Amount>0.0</Amount>
        </TotalAncillaryFeesAndTaxes>
        <TotalDutiesTaxesAndFees>
          <Currency>USD</Currency>
          <Amount>0.0</Amount>
        </TotalDutiesTaxesAndFees>
        <TotalNetChargeWithDutiesAndTaxes>
          <Currency>USD</Currency>
          <Amount>25.86</Amount>
        </TotalNetChargeWithDutiesAndTaxes>
        <Surcharges>
          <SurchargeType>INSURED_VALUE</SurchargeType>
          <Level>PACKAGE</Level>
          <Description>Insured value</Description>
          <Amount>
            <Currency>USD</Currency>
            <Amount>0.0</Amount>
          </Amount>
        </Surcharges>
        <Surcharges>
          <SurchargeType>FUEL</SurchargeType>
          <Level>PACKAGE</Level>
          <Description>FedEx Ground Fuel</Description>
          <Amount>
            <Currency>USD</Currency>
            <Amount>1.69</Amount>
          </Amount>
        </Surcharges>
      </ShipmentRateDetail>
      <RatedPackages>
        <GroupNumber>0</GroupNumber>
        <PackageRateDetail>
          <RateType>PAYOR_ACCOUNT_PACKAGE</RateType>
          <RatedWeightMethod>ACTUAL</RatedWeightMethod>
          <BillingWeight>
            <Units>LB</Units>
            <Value>25.0</Value>
          </BillingWeight>
          <BaseCharge>
            <Currency>USD</Currency>
            <Amount>24.17</Amount>
          </BaseCharge>
          <TotalFreightDiscounts>
            <Currency>USD</Currency>
            <Amount>0.0</Amount>
          </TotalFreightDiscounts>
          <NetFreight>
            <Currency>USD</Currency>
            <Amount>24.17</Amount>
          </NetFreight>
          <TotalSurcharges>
            <Currency>USD</Currency>
            <Amount>1.69</Amount>
          </TotalSurcharges>
          <NetFedExCharge>
            <Currency>USD</Currency>
            <Amount>25.86</Amount>
          </NetFedExCharge>
          <TotalTaxes>
            <Currency>USD</Currency>
            <Amount>0.0</Amount>
          </TotalTaxes>
          <NetCharge>
            <Currency>USD</Currency>
            <Amount>25.86</Amount>
          </NetCharge>
          <TotalRebates>
            <Currency>USD</Currency>
            <Amount>0.0</Amount>
          </TotalRebates>
          <Surcharges>
            <SurchargeType>INSURED_VALUE</SurchargeType>
            <Level>PACKAGE</Level>
            <Description>Insured value</Description>
            <Amount>
              <Currency>USD</Currency>
              <Amount>0.0</Amount>
            </Amount>
          </Surcharges>
          <Surcharges>
            <SurchargeType>FUEL</SurchargeType>
            <Level>PACKAGE</Level>
            <Description>FedEx Ground Fuel</Description>
            <Amount>
              <Currency>USD</Currency>
              <Amount>1.69</Amount>
            </Amount>
          </Surcharges>
        </PackageRateDetail>
      </RatedPackages>
    </RatedShipmentDetails>
  </RateReplyDetails>
</RateReply>

用于读取xml响应的方法:

private void ReadResponseData(string response)
{
    RatesModel entities = new RatesModel();
    var req = entities.ShippingRequests;
    XDocument xmlResponse = XDocument.Parse(response.ToString());
    XNamespace ns = "http://fedex.com/ws/rate/v24";

    try
    {

        foreach (XElement r in xmlResponse.Descendants(ns + "RateReply"))
        {
            var totalCost = r.Element("RateReplyDetails").Element("RatedShipmentDetails").Element("ShipmentRateDetail").Element("TotalNetCharge").Element("Amount").Value;

        }                
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}

我想从响应xml中获取几个元素的值,以在我的应用程序中使用。

1 个答案:

答案 0 :(得分:3)

由于仅在NullReferenceException部分中提供了名称空间,所以得到了foreach。您应该在每个.Element调用中使用名称空间。 / p>

r.Element(ns + "RateReplyDetails").Element(ns + "RatedShipmentDetails")...