简体   繁体   English

如何从此XML请求中检索日期?

[英]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: 我正在尝试从此XML请求中获取开始日期和结束日期以及酒店代码:

<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);

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

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