我需要使用XML文件创建缓存。这是我将要使用的方法。我希望此方法基于key-product_name返回id。所以我希望它以编程方式一次创建一个缓存,然后只有在找不到密钥时才创建一个[缓存中的新条目]。如果一切看起来都没问题,问题在于获得产品的ID。请指教。我已经包含了代码和xml文件。
public static string getProductId(string product_name)
public static string getTechId(string fieldName)
{
Cache cache = HttpContext.Current.Cache; //neeed to change this.
string cacheNameEpm = product_name + "PrdName";
if (cache[cacheNameEpm] == null)
{
XPathDocument doc = new XPathDocument(HttpContext.Current.Request.MapPath("inc/xml/prd.xml"));
XPathNavigator navigator = doc.CreateNavigator();
string selectName = "/Products/Product/ProductName";
XPathNodeIterator nodes = navigator.Select(selectName);
while (nodes.MoveNext())
{
switch (nodes.Current.Name)
{
case "ProductName":
cacheNameEpm = nodes.Current.Value + "PrdName";
navigator.Select("/Products/Product/ProductId");
navigator.MoveToNext();
if (nodes.Current.Name == "ProductId")
{
id = navigator.Value;
}
cache.Add(cacheNameEpm, id, null, DateTime.Now + new TimeSpan(4, 0, 0), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
break;
}
}
}
return cache[cacheNameEpm] as string;
}
这是xml文件:
<Products>
<Product>
<ProductName>PDPArch</ProductName>
<ProductId>57947</ProductId>
</Product>
<Product>
<ProductName>TYFTType</ProductName>
<ProductId>94384</ProductId>
</Product>
</Products>
答案 0 :(得分:1)
要获取"TYFTType"
的产品ID,您需要此XPath表达式:
/Products/Product[ProductName = 'TYFTType']/ProductId
那么(未经测试,但你得到了想法)的事情是什么:
public static string getProductId(string product_name)
{
Cache cache = HttpContext.Current.Cache;
string cacheNameEpm = product_name + "PrdName";
if (cache[cacheNameEpm] == null)
{
// let's cache the navigator itself as well
string cacheNameNav = "prd.xml_Navigator";
XPathNavigator navigator = cache[cacheNameNav] as XPathNavigator;
if (navigator == null)
{
XPathDocument doc = new XPathDocument(
HttpContext.Current.Request.MapPath("inc/xml/prd.xml")
);
navigator = doc.CreateNavigator();
cache.Add(
cacheNameNav,
navigator,
null,
DateTime.Now + new TimeSpan(4, 0, 0),
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
null
);
}
string xpath = String.Format(
"/Products/Product[ProductName = '{0}']/ProductId", product_name
);
XPathNavigator product_id = navigator.SelectSingleNode(xpath);
if (product_id.IsNode)
{
cache.Add(
cacheNameEpm,
product_id.Value,
null,
DateTime.Now + new TimeSpan(4, 0, 0),
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
null
);
}
}
return cache[cacheNameEpm] as string;
}
以上有两个小问题: