简体   繁体   English

如何从 SOAP 响应中检索元素值

[英]How to retrieve an element value from SOAP response

I have the following SOAP response and I want to get the value from the tag element a:Year1.我有以下 SOAP 响应,我想从标记元素 a:Year1 中获取值。 How can I achieve this using c#?我如何使用 c# 实现这一目标?

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetPerformanceAndRiskByTypeCodeResponse xmlns="http://tempuri.org/">
      <GetPerformanceAndRiskByTypeCodeResult xmlns:a="http://schemas.datacontract.org/2004/07/FE.Toolkit.Services.DataContracts.ResponsiveChartingTool" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <IsSuccessful xmlns="http://schemas.datacontract.org/2004/07/FE.Toolkit.Services.DataContracts">false</IsSuccessful>
        <ResponseCode xmlns="http://schemas.datacontract.org/2004/07/FE.Toolkit.Services.DataContracts">0</ResponseCode>
        <ResponseMessage i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/FE.Toolkit.Services.DataContracts" />
        <TotalRows xmlns="http://schemas.datacontract.org/2004/07/FE.Toolkit.Services.DataContracts">0</TotalRows>
        <a:CalendarPerformanceAs>2019-12-31T00:00:00</a:CalendarPerformanceAs>
        <a:CumulativePerformanceAs>2020-10-01T00:00:00</a:CumulativePerformanceAs>
        <a:DiscretePerformanceAs>2020-09-30T00:00:00</a:DiscretePerformanceAs>
        <a:InstrumentInformation>
          <a:InstrumentInformation>
            <a:CalendarPerformance>
              <a:IncomeBasisPriceType>2</a:IncomeBasisPriceType>
              <a:PerformanceCurrency>USD</a:PerformanceCurrency>
              <a:Year1>19.031154</a:Year1>
              <a:Year2>-13.434495</a:Year2>
              <a:Year3>23.004020</a:Year3>
              <a:Year4>-5.584117</a:Year4>
              <a:Year5>-2.882996</a:Year5>
            </a:CalendarPerformance>
          </a:InstrumentInformation>
        </a:InstrumentInformation>
        <a:RiskAs>2020-09-30T00:00:00</a:RiskAs>
      </GetPerformanceAndRiskByTypeCodeResult>
    </GetPerformanceAndRiskByTypeCodeResponse>
  </s:Body>
</s:Envelope>

I tried the following but no luck:我尝试了以下但没有运气:

var str = XElement.Parse(xml.Response.XmlResponse.ToString()); 
var result = str.Element("InstrumentInformation").Element("InstrumentInformation")[0].Element("CalendarPerformance").Element("Year1").Value; 
Console.WriteLine("RESULT" + result);

The error is错误是

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

You need to deal with the namespace of the element.您需要处理元素的命名空间。 You can ignore it and use the local name but it is more robust to include it:您可以忽略它并使用本地名称,但包含它会更可靠:

XNamespace ns = "http://schemas.datacontract.org/2004/07/FE.Toolkit.Services.DataContracts.ResponsiveChartingTool";

var y1 = str.Descendants().Elements(ns + "Year1").FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM