繁体   English   中英

如何使用C#和WPF通过编程方式计算父XML节点内子XML节点的数量?

[英]How to count by programmatic way the quantity of child XML nodes within parent XML node using C# and WPF?

我编写了一个WPF应用程序,该应用程序是两层的主细节,并使用XML文件作为数据源。 下面,我显示此XML文件的内容。 该文件放在项目中包含的Data文件夹中,文件本身也包含在项目中。 该文件的名称是Books.xml。

<?xml version="1.0" encoding="utf-8" ?>
<Books xmlns="">
  <Category name="Computer Programming">
    <Book>
      <Author>H. Schildt</Author>
      <Title>C# 4.0 The Complete Reference</Title>
    </Book>
  </Category>
  <Category name="Art Editions">
    <Book>
      <Author>M. Cervantes</Author>
      <Title>The Ingenious Gentleman Don Quixote of La Mancha </Title>
    </Book>
    <Book>
      <Author>P. Ronsard</Author>
      <Title>Les Amours</Title>
    </Book>
  </Category>
</Books>

我需要计算每个Category节点中Book节点的数量并存储结果。 我该怎么做?

您可以使用LINQ-to-XML的XDocument实现此目的,例如:

var doc = XDocument.Parse("put_path_to_xml_file_here.xml");
//loop through all <Category>
foreach (var category in doc.Root.Elements("Category"))
{
    //count <Book> elements within current <Category> element
    var numberOfBooks = category.Elements("Book").Count();
    //print the category name and the number of book elements
    Console.WriteLine((string)category.Attribute("name") + " : " + numberOfBooks);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM