Rahul Nagrale
Rahul Nagrale

Reputation: 93

How to get the XML Element Attribute values?

I have below xml from which I am trying to get the value of HotelCrossRef Element ResponseHotelCode attribute.

I have tried below code but I am getting 0 Count in XmlNodeList

string xmlResp = @"<?xml version=""1.0"" encoding=""utf-8""?><OTA_HotelDescriptiveContentNotifRS xmlns=""http://www.opentravel.org/OTA/2003/05"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.opentravel.org/OTA/2003/05 OTA_HotelDescriptiveContentNotifRS.xsd"" TimeStamp=""2015-07-31T12:36:23-00:00"" Target=""Test"" Version=""3.000"">
<UniqueID Type=""10"" ID=""1460495"" />
<TPA_Extensions>
<HotelCrossRefs>
<HotelCrossRef RequestHotelCode=""101010"" ResponseHotelCode=""1460495"" />
</HotelCrossRefs>
</TPA_Extensions>
<Success />
</OTA_HotelDescriptiveContentNotifRS>";

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlResp);

XmlNodeList xnList = xmlDocument.SelectNodes("/OTA_HotelDescriptiveContentNotifRS/TPA_Extensions/HotelCrossRefs");
foreach (XmlNode xn in xnList)
{
    if (xn.HasChildNodes)
    {
        foreach (XmlNode childNode in xn.ChildNodes)
        {
            string id = childNode.Attributes["ResponseHotelCode"].Value; 
            Console.WriteLine(id);
        }
    }
}

Upvotes: 0

Views: 70

Answers (1)

Magnetron
Magnetron

Reputation: 8543

You have a namespace problem, your xml has a default namespace that you must declare when selecting nodes. try the following:

string xmlResp = @"<?xml version=""1.0"" encoding=""utf-8""?><OTA_HotelDescriptiveContentNotifRS xmlns=""http://www.opentravel.org/OTA/2003/05"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.opentravel.org/OTA/2003/05 OTA_HotelDescriptiveContentNotifRS.xsd"" TimeStamp=""2015-07-31T12:36:23-00:00"" Target=""Test"" Version=""3.000"">
    <UniqueID Type=""10"" ID=""1460495"" />
    <TPA_Extensions>
    <HotelCrossRefs>
    <HotelCrossRef RequestHotelCode=""101010"" ResponseHotelCode=""1460495"" />
    </HotelCrossRefs>
    </TPA_Extensions>
    <Success />
    </OTA_HotelDescriptiveContentNotifRS>";

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlResp);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("xn", "http://www.opentravel.org/OTA/2003/05");

XmlNodeList xnList = xmlDocument.SelectNodes("/xn:OTA_HotelDescriptiveContentNotifRS/xn:TPA_Extensions/xn:HotelCrossRefs", nsmgr);
foreach (XmlNode xn in xnList)
{
    if (xn.HasChildNodes)
    {
        foreach (XmlNode childNode in xn.ChildNodes)
        {
            string id = childNode.Attributes["ResponseHotelCode"].Value;
            Console.WriteLine(id);
        }
    }
}

Note that I added another parameter in the SelectNodes method

Upvotes: 3

Related Questions