简体   繁体   中英

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. Below I show the content of this XML file. This file is put in Data folder that is included in project and file itself is included in project too. The name of this file is 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. How can I do it?

You can use LINQ-to-XML's XDocument to achieve that, for example :

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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