gpt4 book ai didi

c# - 不用for循环将数据写入xml

转载 作者:行者123 更新时间:2023-11-30 22:04:51 26 4
gpt4 key购买 nike

我正在研究 NopCommerce 2.40,并尝试使用 C# 生成站点地图以将其提交给谷歌网站管理员工具。

我的代码

_writer = new XmlTextWriter(stream, Encoding.UTF8);
_writer.Formatting = Formatting.Indented;
_writer.WriteStartDocument();
_writer.WriteStartElement("urlset");
_writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
_writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
_writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

GenerateUrlNodes();

_writer.WriteEndElement();
_writer.Close();

在这个 GenerateUrlNodes() 方法中调用了不同的方法例如

            WriteStores();
WriteStoresCategories();
WriteStoresProducts();

在写商店产品的第三种方法中。

foreach (var store in stores)
{

//TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
if (store.Id != 1)
{
var products = _productService.SearchProducts(0, 0, null, null, null, 0, null, false, 1, new List<int>(), ProductSortingEnum.Position, 0, int.MaxValue, store.Id, false);
foreach (var product in products)
{
var url = string.Format("{0}s/{1}/{2}/p/{3}/{4}", _webHelper.GetStoreLocation(false), store.Id, store.GetSeName(), product.Id, product.GetSeName());
var updateFrequency = UpdateFrequency.Weekly;
var updateTime = product.UpdatedOnUtc;
WriteUrlLocation(url, updateFrequency, updateTime);


}

}
}

它花费的时间太长,因为有多家商店,每家商店有 5 到 6k 种产品。因此,当我尝试将此站点地图提交给谷歌时,它会抛出超时错误。有没有办法优化这个或者避免for循环生成xml

谁能帮我解决这个问题?

最佳答案

这里要做的第一件事是去除冗余。看起来您为每个产品调用一次 _webHelper.GetStoreLocation(false),为每个产品调用两次 store.GetSeName() - 但两者都不依赖于产品。所以作为一个直接的事情:

var location = _webHelper.GetStoreLocation(false);
foreach (var store in stores)
{
var seName = store.GetSeName();
//TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
if (store.Id != 1)
{
var products = _productService.SearchProducts(0, 0, null, null, null, 0, null, false, 1, new List<int>(), ProductSortingEnum.Position, 0, int.MaxValue, store.Id, false);
foreach (var product in products)
{
var url = string.Format("{0}s/{1}/{2}/p/{3}/{4}", location, store.Id, seName, product.Id, seName);
var updateFrequency = UpdateFrequency.Weekly;
var updateTime = product.UpdatedOnUtc;
WriteUrlLocation(url, updateFrequency, updateTime);
}
}
}

SearchProducts 显然是针对每个商店的,因为它涉及到 store.Id,所以我们不能推广它;然而,看起来 stores 循环是可以并行化的;例如,如果这是进行 http 调用,则很值得在这里研究 Parallel.ForEach,但问题就变成了排序和并发;您可能需要使用 Parallel 创建每个的结果(作为字符串或类似字符串),然后当所有字符串都可用时,循环执行实际写入 - 从而保留原始顺序。

关于c# - 不用for循环将数据写入xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com