解析带前缀的xml

geo.xml

<?xml version="1.0" encoding="utf-8"?>
<q1:HotelGeoList xmlns:q1="http://api.elong.com/staticInfo/">
  <q1:HotelGeo>
    <q1:id>1</q1:id>
    <q1:country>中国</q1:country>
    <q1:provinceName>北京                </q1:provinceName>
    <q1:provinceId>0100</q1:provinceId>
    <q1:cityName>北京</q1:cityName>
    <q1:cityCode>0101</q1:cityCode>
    <q1:properties>2098</q1:properties>
    <q1:url>http://www.elong.com/hotels/Search.aspx?raCityName=%u5317%u4EAC</q1:url>
/// <summary>
        /// 根据城市名称获取城市ID
        /// </summary>
        /// <param name="cityName"></param>
        /// <returns></returns>
        private string GetCityIdByName(string cityName)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Current.Server.MapPath("/xmlhotelfile/geo_cn.xml"));

            XmlElement root = doc.DocumentElement;

            XmlNodeList list1 = root.GetElementsByTagName("q1:HotelGeo");
            int len = list1.Count;
            for (int i = 0; i < len; i++)
            {
                string cityId = list1[i]["q1:cityCode"].InnerText;

                if (list1[i]["q1:cityName"].InnerText == cityName)
                {
                    i = len;
                    return cityId;
                    break;
                }
            }
            return "";
        }

上面循环哪里,据同事说,用变量len把他存起来,效率会好一点,不用每次都计算数量。如果是每次循环list1.count都要计算数量的话,那是挺伤效率的。

原文地址:https://www.cnblogs.com/hougelou/p/2854544.html