简体   繁体   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?

I write a WPF application which is two-level master-details and uses XML file as data source. 我编写了一个WPF应用程序,该应用程序是两层的主细节,并使用XML文件作为数据源。 Below I show the content of this XML file. 下面,我显示此XML文件的内容。 This file is put in Data folder that is included in project and file itself is included in project too. 该文件放在项目中包含的Data文件夹中,文件本身也包含在项目中。 The name of this file is Books.xml. 该文件的名称是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>

I'm in need of counting of quantity of Book nodes within each Category node and storing the results. 我需要计算每个Category节点中Book节点的数量并存储结果。 How can I do it? 我该怎么做?

You can use LINQ-to-XML's XDocument to achieve that, for example : 您可以使用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