Skip to main content
 首页 » 编程设计

c#之如何使用 C# 和 XML 进行高效计数

2024年02月23日15zhwl

我有一个 XML 格式的产品数据库。对于每个产品,我都有其宽度 W、高度 H 和价格 P。

给定一个包含 W、H 和 P 的产品,我想计算宽度小于 W 的产品数量,并对高度 < H 和价格 < P 的产品进行单独计数。这意味着 3 个单独且独立的数字结果从计数。

使用 C# 执行此操作的有效方法是什么?显然,我只想遍历 XML 文件中的每个元素一次。

XML 文件由以下节点组成,并已读入 XDocument 对象:

<product><name>abc</name><W>7</W><H>3</H><P>40</P></product> 

请您参考如下方法:

像这样的东西会起作用

  XDocument doc = XDocument.Parse(xml); 
 
  int heightCount = 0; 
  int widthCount = 0; 
  int priceCount = 0; 
 
  int heightThreshold = 3; 
  int widthThreshold = 1; 
  int priceThreshold = 1; 
 
  foreach (var product in doc.Descendants("product")) 
  { 
    int height = Convert.ToInt32(product.Element("H").Value); 
    int width = Convert.ToInt32(product.Element("W").Value); 
    int price = Convert.ToInt32(product.Element("P").Value); 
 
    if (height < heightThreshold) 
    { 
      heightCount++; 
    } 
 
    if (width < widthThreshold) 
    { 
      widthCount++; 
    } 
 
    if (price < priceThreshold) 
    { 
      priceCount++; 
    }        
  } 

虽然这没有任何保护措施,因此如果您的产品元素不包含每个 H、W 和 P 元素的整数值(或者其中一个元素不存在),它就会中断。您需要添加一些 null 和转换检查。