Question

This is my code to retrieve an element from XML:

private async Task<XElement> PostAsXmlRequestAsync(XElement parameter, CancellationToken responseToken)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Constants.url);
        HttpResponseMessage responseMessage = await client.PostAsXmlAsync(Constants.uri, parameter, responseToken);

        string responseContent = await responseMessage.Content.ReadAsStringAsync();
        XElement responseXml = XElement.Parse(responseContent);

        **bool hasElement = responseXml.Elements("Warnings").Any();
        Console.WriteLine(hasElement);**

        return responseXml;
    }
}

responseXml has a Warnings element, but hasElement is always false.

This is sample XML from the response:

<OTA_VehAvailRateRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.opentravel.org/OTA/2003/05" Target="Qual" Version="2.007">
    <Success /> 
    <Warnings>
        <Warning Type="1" ShortText="FOR RENTERS UNDER 25 YRS OF AGE SEE KEYWORD AGE" RecordID="201" /> 
    </Warnings>
    <VehAvailRSCore>
        <VehRentalCore PickUpDateTime="2014-05-01T10:00:00-05:00" ReturnDateTime="2014-05-03T10:00:00-05:00">
            <PickUpLocation ExtendedLocationCode="LAXT15" LocationCode="LAX" /> 
            <ReturnLocation ExtendedLocationCode="LAXT15" LocationCode="LAX" /> 
        </VehRentalCore>
    </VehAvailRSCore>
</OTA_VehAvailRateRS>
Was it helpful?

Solution

Likely node you are looking for have some namespace instead of default empty namespace (i.e. XML have something like xmlns="http://some-namespace").

You should use version that takes name with namespace to select element. XContainer.Elements article shows both cases as samples:

XNamespace aw = "http://www.adventure-works.com";
var elements = xmlTree.Elements(aw + "Type2");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top