Bumba
Bumba

Reputation: 343

How to get the values of a specific attribute in different nodes?

I have a xml file which looks like

<?xml version="1.0"?>
 <notes>
  <note>
   <to>Tove</to>
   <from add="abc1">Jani</from>
   <heading>Reminder</heading>
   <body>Don't forget me this weekend!</body>
  </note>
  <note>
   <to add="xyz1">Tove</to>
   <from>Jani</from>
   <heading>Reminder</heading>
   <body>Don't forget me this <rref add="10">10</rref> weekend!</body>
   <pol add="adt10"/>
  </note>
 </notes>

I want to get all the values of the attribute add (except from self-closing nodes) from all the different nodes that has that attribute i.e. the output should be an list/array of the values abc1, xyz1, 10. How do I do this using LINQ-TO-XML?

Is there an equivalent of the Descendants method for attributes?

Upvotes: 0

Views: 62

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

You need to filter from the descendants which have attribute add and are not self closing nodes which contains the add attribute.

Something like:

var nodess = from note in Doc.Descendants()
             where note.Attribute("add") !=null && !note.IsEmpty 
             select note.Attribute("add").Value;

foreach(var node in nodess)
{       
   Console.WriteLine(node);
}

You would need to include usings of these two :

using System.Xml.Linq;
using System.Linq;

Output:

abc1

xyz1

10

See the working DEMO Fiddle.

UPDATE:

As per your query about exclude it in the case when has closing tag separate but empty i.e. no value in it :

where note.Attribute("add") !=null && (!note.IsEmpty  || !String.IsNullOrEmpty(note.Value))

Upvotes: 1

Related Questions