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

How to read values from an xml response using XDocument?

尝试从 xml 响应中获取值时出错。错误如下所列。

ERROR: Object reference not set to an instance of an object.

当代码到达代码行 "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 以在我的应用程序中使用。

你得到一个 NullReferenceException 因为你只在 foreach 部分提供命名空间...你应该在每个 .Element 调用中使用命名空间.

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