高效的XML解析

美好的一天,

我正在用C#.Net编写一个程序来管理我店里的产品,

根据给定的链接,我可以检索一个XML文件,其中包含我可以列在店面上的所有可能产品。

XML结构如下所示:

                 

以下是我正在寻找的条目:

  • 最近更新时间
  • StockCode
  • PRODNAME
  • ProdDesc
  • TopCat <—嵌套在Categories标签中。
  • ProdImg
  • ProdPriceExclVAT
  • ProdQ​​ty
  • ProdExternalURL

这一切都很好,事实上我做了:

 public ProductList Parse() { XmlDocument doc = new XmlDocument(); doc.Load(XMLLink); XmlNodeList ProductNodeList = doc.GetElementsByTagName("Product"); foreach (XmlNode node in ProductNodeList) { Product Product = new Product(); for (int i = 0; i < node.ChildNodes.Count; i++) { if (node.ChildNodes[i].Name == "StockCode") { Product.VariantSKU = Convert.ToString(node.ChildNodes[i].InnerText); } if (node.ChildNodes[i].Name == "Brand") { Product.Vendor = Convert.ToString(node.ChildNodes[i].InnerText); } if (node.ChildNodes[i].Name == "ProdName") { Product.Title = Convert.ToString(node.ChildNodes[i].InnerText); Product.SEOTitle = Product.Title; Product.Handle = Product.Title; } if (node.ChildNodes[i].Name == "ProdDesc") { Product.Body = Convert.ToString(node.ChildNodes[i].InnerText); Product.SEODescription = Product.Body; if (Product.Body == "") { Product.Body = "ERROR"; Product.SEODescription = "ERROR"; } } if (node.ChildNodes[i].Name == "Categories") { if (!tempList.Categories.Contains(node.ChildNodes[i].ChildNodes[0].InnerText)) { if (!tempList.Categories.Contains("All")) { tempList.Categories.Add("All"); } tempList.Categories.Add(node.ChildNodes[i].ChildNodes[0].InnerText); } Product.Type = Convert.ToString(node.ChildNodes[i].ChildNodes[0].InnerText); } if (node.ChildNodes[i].Name == "ProdImg") { Product.ImageSrc = Convert.ToString(node.ChildNodes[i].InnerText); if (Product.ImageSrc == "") { Product.ImageSrc = "ERROR"; } Product.ImageAlt = Product.Title; } if (node.ChildNodes[i].Name == "ProdPriceExclVAT") { float baseprice = float.Parse(node.ChildNodes[i].InnerText); double Costprice = ((baseprice * 0.14) + (baseprice * 0.15) + baseprice); Product.VariantPrice = Costprice.ToString("0.##"); } } Product.Supplier = "Pinnacle"; if (!tempList.Suppliers.Contains(Product.Supplier)) { tempList.Suppliers.Add(Product.Supplier); } tempList.Products.Add(Product); } return tempList; } } 

然而问题是,这样做的方式大约需要10秒才能完成,而这只是我必须解析的多个这样的文件中的第一个。

我正在寻找解析此XML文件的最有效方法,获取上面提到的所有字段的数据。

编辑:我在使用预先下载的文件副本运行时以及在运行时从服务器下载文件时对代码进行基准测试:

  • 本地副本:5秒。

  • 没有本地副本:7.30秒。

对于大型XML文件,您必须使用XmlReader。 以下代码将一次读取一个产品。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { XmlReader reader = XmlReader.Create("filename"); while(!reader.EOF) { if (reader.Name != "Product") { reader.ReadToFollowing("Product"); } if (!reader.EOF) { XElement product = (XElement)XElement.ReadFrom(reader); string lastUpdated = (string)product.Element("lastUpdated"); } } } } }