>source

다음 SOAP 응답에서 ClubMembershipId를 가져 오려고하면 "system.xml.linq.xcontainer.element (...)가 null을 반환했습니다."라는 메시지가 표시됩니다.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <soapenv:Body>    <ns1:SearchClubMembershipsResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://DefaultNamespace">  <SearchClubMembershipsReturn xsi:type="ns2:Response" xmlns:ns2="http://searchClubMemberships.clubmembership.V300">    <ClubMemberships soapenc:arrayType="ns3:ClubMembership[1]" xsi:type="soapenc:Array" xmlns:ns3="http://_clubmembership.clubmembership.V300" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">      <ClubMemberships xsi:type="ns3:ClubMembership">        <CancelDate xsi:type="xsd:dateTime" xsi:nil="true" />        <ClubCancellationReason xsi:type="xsd:string"></ClubCancellationReason>        <ClubCancellationReasonID xsi:type="xsd:string"></ClubCancellationReasonID>        <ClubID xsi:type="xsd:string"></ClubID>        <ClubMembershipID xsi:type="xsd:string">TestID</ClubMembershipID>        <ClubName xsi:type="xsd:string"></ClubName>        <Contact xsi:type="ns3:Contact">          <Address xsi:type="xsd:string"></Address>          <Address2 xsi:type="xsd:string"></Address2>          <BirthDate xsi:type="xsd:dateTime"></BirthDate>          <City xsi:type="xsd:string"></City>          <Company xsi:type="xsd:string"></Company>          <ContactID xsi:type="xsd:string"></ContactID>          <CountryCode xsi:type="xsd:string"></CountryCode>          <CustomerNumber xsi:type="xsd:double"></CustomerNumber>          <Email xsi:type="xsd:string"></Email>          <FirstName xsi:type="xsd:string"></FirstName>          <LastName xsi:type="xsd:string"></LastName>          <Phone xsi:type="xsd:string"></Phone>          <StateCode xsi:type="xsd:string"></StateCode>          <ZipCode xsi:type="xsd:string"></ZipCode>        </Contact>        <CreditCardID xsi:type="xsd:string"></CreditCardID>        <CurrentClubMembershipStatus xsi:type="xsd:string"></CurrentClubMembershipStatus>        <CurrentNumberOfShipments xsi:type="xsd:double"></CurrentNumberOfShipments>        <DateAdded xsi:type="xsd:dateTime"></DateAdded>        <DateModified xsi:type="xsd:dateTime"></DateModified>        <GiftMessage xsi:type="xsd:string"></GiftMessage>        <IsGift xsi:type="xsd:boolean"></IsGift>        <IsPickup xsi:type="xsd:boolean"></IsPickup>        <IsPrePay xsi:type="xsd:boolean"></IsPrePay>        <LastProcessedDate xsi:type="xsd:dateTime"></LastProcessedDate>        <Notes xsi:type="xsd:string"></Notes>        <OnHoldStartDate xsi:type="xsd:dateTime"></OnHoldStartDate>        <OnHoldUntilDate xsi:type="xsd:dateTime"></OnHoldUntilDate>        <PickupHandlingFee xsi:type="xsd:double"></PickupHandlingFee>        <PickupLocationCode xsi:type="xsd:string"></PickupLocationCode>        <PrePayOrderNumber xsi:type="xsd:double" xsi:nil="true" />        <RetainClubPrivileges xsi:type="xsd:boolean"></RetainClubPrivileges>        <SalesAssociate xsi:type="xsd:string"></SalesAssociate>        <SalesAssociateID xsi:type="xsd:string"></SalesAssociateID>        <ShipTo xsi:type="xsd:string"></ShipTo>        <ShippingAddress xsi:type="ns3:ShippingAddress" xsi:nil="true" />        <SignupDate xsi:type="xsd:dateTime"></SignupDate>        <SourceCode xsi:type="xsd:string"></SourceCode>        <TotalNumberOfShipments xsi:type="xsd:double" xsi:nil="true" />        <WebsiteID xsi:type="xsd:string"></WebsiteID>      </ClubMemberships>    </ClubMemberships>    <Errors soapenc:arrayType="ns4:Error[0]" xsi:type="soapenc:Array" xmlns:ns4="http://response.base.V300" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" />    <IsSuccessful xsi:type="xsd:boolean"></IsSuccessful>    <RecordCount xsi:type="xsd:double"></RecordCount>  </SearchClubMembershipsReturn></ns1:SearchClubMembershipsResponse>  </soapenv:Body></soapenv:Envelope>

다음은 LINQ to XML을 사용하여 ClubMembershipId를 가져 오는 방법입니다.

using (WebResponse services= request.GetResponse())
                {
                    using (StreamReader rd= new StreamReader(services.GetResponseStream()))
                    {
                        var ServiceResult= rd.ReadToEnd();
                        XDocument xdoc= new XDocument();
                        xdoc= XDocument.Parse(ServiceResult);
                        var xDocResult= (from x in xdoc.Descendants("ClubMemberships").Descendants("ClubMemberships")
                                          select new S_WD_ClubMembership_Updates
                                          {
                                              ClubMembershipId= x.Element("ClubMembershipID").Value
                                          });
                        var contactsList1= xDocResult.ToList();

또한 var xDocResult= (xdoc.Descendants ( "ClubMemberships")의 x에서 시도했지만 실패했습니다.

내게 중첩 된 연락처 요소가 있다는 것이 문제일까요?

붙여 넣은 code는 주어진 xml에서 잘 작동합니다.

Alexander2021-04-18 02:25:26

Console.Write (ServiceResult)가 올바른 xml을 표시합니까?

Greg2021-04-18 02:25:26

@Greg. 그렇습니다. xml은 스키마와 일치합니다. var contactList1에 중단 점을두면 xDocResult를 열거하려고 할 때 "개체 참조가 개체의 인스턴스로 설정되지 않았습니다"라는 메시지가 나타납니다. S_WD_ClubMembership_Updates가 어떻게 생겼는지 표시하도록 게시물을 편집했습니다.

user16471602021-04-18 02:25:26

StreamReader (services.GetResponseStream ())를 StreamReader (@ "c : \ temp \ test.xml")로 바꾸고 (그리고 test.xml 파일에서 예상되는 XML을 덤프) 실행할 수 있습니까? 3 인용 인 것 같습니다. 근본 원인은 services.GetResponseStream ()에서 예상치 못한 일 가능성이 높습니다. 그러나 테스트를 실행하면 이것이 사실인지 확인해야합니다.

Greg2021-04-18 02:25:26

@Greg. 나는 당신이 제안한대로했지만 여전히 같은 오류가 발생합니다.

user16471602021-04-18 02:25:26
  • 답변 # 1

    알렉산더와 XML 파싱이 작동한다는 데 동의합니다. HTTP 요청 /응답에 문제가 있어야합니다. 내가 사용한 code는 다음과 같습니다.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME= @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                string ServiceResult= File.ReadAllText(FILENAME);
                XDocument xdoc= new XDocument();
                xdoc= XDocument.Parse(ServiceResult);
                var xDocResult= (from x in xdoc.Descendants("ClubMemberships").Descendants("ClubMemberships")
                                  select new S_WD_ClubMembership_Updates
                                  {
                                      ClubMembershipId= x.Element("ClubMembershipID").Value
                                  });
                var contactsList1= xDocResult.ToList();
            }
        }
        public class S_WD_ClubMembership_Updates
        {
            public string ClubMembershipId { get; set; }
        }
    }
    

    추가 정보로 게시물을 업데이트했습니다.

    user16471602021-04-18 02:25:26
  • 이전 python : requests_html을 사용하여 javascript를 클릭하는 방법
  • 다음 java : onBackPressed () 메서드를 재정의합니다. 활동을 종료하려면 뒤로 버튼을 두 번 클릭해야합니다.