我正在从 expedia API 获取航类详细信息,请查看下面的链接了解 XML 格式。
结果输出包含Rateinfo,然后包含航类详细信息作为单独的节点,并且rateinfo 和flightsegment 之间没有关系。 通常我将 XML 加载到数据集中并使用数据集填充记录,但在这种情况下,费率和航段之间没有关系,我将如何在 C# 中解析此 XML。我需要向用户显示航段和相应的费率。
http://api.ean.com/ean-services/rs/air/200919/xmlinterface.jsp?cid=55505&resType=air&intfc=ws&apiKey=fc9hjrvrur9vr4y2dqa249w4&xml=<AirSessionRequest method="getAirAvailability"><AirAvailabilityQuery><originCityCode>MCI</originCityCode><destinationCityCode>CLT</destinationCityCode><departureDateTime>09/01/2011 01:00 AM</departureDateTime><returnDateTime>09/04/2011 01:00 AM</returnDateTime><fareClass>Y</fareClass><tripType>R</tripType><Passengers><adultPassengers>2</adultPassengers></Passengers><xmlResultFormat>1</xmlResultFormat><searchType>2</searchType></AirAvailabilityQuery></AirSessionRequest>
最佳答案
使用上面提到的 LINQ to XML 作为 Braveyard 可能会有所帮助。您可以使用 LINQ 分解 XML 并一次处理一组费率信息和航段。如果您使用匿名类型,您可以在一种费率信息和关联的航段之间建立自己的连接,然后将其存储在数据库中。
这是一个帮助您走上这条路的粗略示例:
XDocument xDoc = new XDocument();
xDoc = xDoc.Parse(responseXML); // Parse will take a string and load the XDocument with it
// You can also use Load to load from a file, StreamReader, etc.
// First, grab a collection of all the AirAvailabilityReply
var airAvailability = from x in xDoc.Descendants("AirAvailabilityReply")
select x;
// Now loop through each of the query results in the collection
foreach (var available in airAvailability)
{
// Get the rate info
var rates = from r in available.Descendants("RateInfo")
select new RateInfo {
NativeBaseFare = r.Element("nativeBaseFare").Value,
NativeTotalPrice = r.Element("NativeTotalPrice").Value,
// etc
};
// Get the flight segment info
var segments = from s in available.Descendants("FlightSegment")
select new FlightSegment {
SegmentOutgoing = s.Element("segmentOutgoing").Value,
AirlineCode = s.Element("airlineCode").Value,
// etc
};
// Now you can take RateInfo (should only be one) and the FlightSegments (should be a collection of FlightSegments) and put them into your database.
}
在上面的示例中,我假设您有两个类(RateInfo 和 FlightSegment),并且您将使用 XML 中的相应值填充属性。
这可能不是最有效的示例,但希望它能让您了解如何使用 LINQ to XML 解决此问题。
关于c# - 在 C# 中解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7212426/