XElement Linq query to count number of decendant elements that match attribute value

21 Views Asked by At

I'm trying to find the number of child elements of where the 'index' attribute matches '2'. I'm expecting an integer value of 2.

My code compiles but generates an error at runtime.

My xml looks like this.

<?xml version="1.0" encoding="utf-8"?>
<dataset>
  <bootfilescomponents>
    <bootfiles index="1">
      <name>Boot Files v2.0</name>
      <file path="File1"></file>
    </bootfiles>
    <bootfiles index="2">
      <name>Boot Files v1.0</name>
      <file path="File1"></file>
      <file path="File2"></file>
    </bootfiles>
    <bootfiles index="3">
      <name>Boot Files v1.3</name>
      <file path="File1"></file>
      <file path="File2"></file>
      <file path="File3"></file>
    </bootfiles>
  </bootfilescomponents>
</dataset>

And here's the code.

xe = XElement.Load("dataset.xml")
Dim NumberOfMatches As Integer = xe.Descendants("bootfiles").Elements("file").Count(Function(x) x.Attribute("index").Value = "2")

Can anyone help me understand where I've gone wrong?

edit: A solution using LINQ

    Dim ct As Integer = 0
    Dim nm As String = "file"
    ct = (From el In xe.Descendants(nm)
            Where el.Parent.Name.LocalName = "bootfiles" AndAlso
            el.Parent.@index = "2"
            Select el).Count
0

There are 0 best solutions below