简体   繁体   中英

How can I retrieve date from this XML request?

I am trying to get the start date and end date moreover the hotel code from this XML request:

<OTA_HotelAvailGetRQ xmlns="http://www.opentravel.org/OTA/2003/05" EchoToken="201905140331" TimeStamp="2019-05-14T15:31:09.184+08:00" Version="2.3" PrimaryLangID="en-us">
    <POS>
        <Source>
            <RequestorID MessagePassword="NDMhc@219" Type="5" ID="2363">
                <CompanyName Code="C" CodeContext="963"/>
            </RequestorID>
        </Source>
    </POS>
    <HotelAvailRequests>
        <HotelAvailRequest>
            <DateRange Start="2019-05-14" End="2019-05-19"/>
            <RatePlanCandidates>
                <RatePlanCandidate>
                    <HotelRefs>
                        <HotelRef HotelCode="26604"/>
                    </HotelRefs>
                </RatePlanCandidate>
            </RatePlanCandidates>
            <RoomTypeCandidates>
                <RoomTypeCandidate Quantity="1">
                    <GuestCounts>
                        <GuestCount AgeQualifyingCode="10" Count="2"/>
                    </GuestCounts>
                </RoomTypeCandidate>
            </RoomTypeCandidates>
        </HotelAvailRequest>
    </HotelAvailRequests>
</OTA_HotelAvailGetRQ>

I have tried using this code:

var rootElement = XElement.Parse(doc.ToString());
var date = rootElement.Element("OTA_HotelAvailGetRQ").Element("HotelAvailRequest").Element("DateRange").Attribute("Start").Value; 
Console.WriteLine(date);

but I get an error:

Object reference not set to an instance of an object

Try this way:

XDocument doc = XDocument.Load("xml.xml");
XNamespace ns = "http://www.opentravel.org/OTA/2003/05";
XElement dateRange = doc.Descendants(ns + "DateRange").FirstOrDefault();
DateTime dateStart = DateTime.Parse(dateRange.Attribute("Start").Value);
DateTime dateEnd = DateTime.Parse(dateRange.Attribute("End").Value);
XElement hotelRef = doc.Descendants(ns + "HotelRef").FirstOrDefault();
int hotelCode = int.Parse(hotelRef.Attribute("HotelCode").Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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