Skip to main content
 首页 » 编程设计

c#之使用 XDocument 计算 XML 元素内同名的 ChildElements

2024年02月06日12lovecherry

我有一个看起来像这样的 XML 文件 -

<SST_SignageCompConfig> 
  <Items> 
    <Item> 
      <Index>0</Index> 
      <Type>1</Type> 
      <Duration>7</Duration> 
      <Name>Branding-Colours-for-business.jpg</Name> 
    </Item> 
    <Item> 
      <Index>1</Index> 
      <Type>1</Type> 
      <Duration>7</Duration> 
      <Name>Flower of Life Meditation - Copy.png</Name> 
    </Item> 
</Items> 
</SST_SignageCompConfig> 

我需要计算 Items 元素中有多少个 Item 元素。
即有多少张图片。

我正在使用 XDocument,所以我的 XML 文件是这样加载的 -

string configurationPath = System.IO.Path.Combine("C:\\SST Software\\DSS\\Compilations\\" + compName + @"\\Comp.cfg"); 
XDocument filedoc = XDocument.Load(configurationPath); 

我已经尝试了以下的多种变体,所有变体都返回了一个空对象引用异常

foreach (var item in filedoc.Element("SST_SignageCompConfig").Element("Items").Element("Item").Nodes()) 
{ 
    string name = filedoc.Element("SST_SignageCompConfig").Element("Items").Element("Item").Attribute("Name").ToString(); 
    files.Append(name + "|"); 
} 

我找到了无数关于如何计算一个元素中有多少个不同子元素的示例,但我需要知道存在多少个相同元素实例.

谁能指出我正确的方向?

请您参考如下方法:

您可以像这样选择所有名称:

var names = from item in filedoc.Descendants("Item") 
            select (string)item.Element("Name"); 

或者没有查询语法:

var names = filedoc.Descendants("Item").Elements("Name").Select(e => e.Value); 

您只能通过以下方式获得唯一名称:

var uniqueNames = names.Distinct();