如何获取XML元素属性值?

时间:2018-07-16 15:18:28

标签: c# xml linq

我在xml下面,尝试从中获取HotelCrossRef元素ResponseHotelCode属性的值。

我尝试了以下代码,但在XmlNodeList中得到了0计数

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

1 个答案:

答案 0 :(得分:3)

您遇到一个名称空间问题,您的xml具有一个默认的名称空间,在选择节点时必须声明它。尝试以下操作:

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

请注意,我在SelectNodes方法中添加了另一个参数