我正在尝试从此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>
我尝试使用此代码:
var rootElement = XElement.Parse(doc.ToString());
var date = rootElement.Element("OTA_HotelAvailGetRQ").Element("HotelAvailRequest").Element("DateRange").Attribute("Start").Value;
Console.WriteLine(date);
但是我得到一个错误:
对象引用未设置为对象的实例
答案 0 :(得分:1)
尝试这种方式:
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);