Search code examples
asp.netxmllinquniquexmlreader

How to check the uniqueness of an attribute in an XML file


If I have an XML file and I want to check the uniqueness of the attribute id of each element like the following document:

<classes columns="id,name,short,classroomids,teacherid,grade,customfield1">
  <class id="0ini" name="Initial Class" short="Init" teacherid="" classroomids="" grade="" customfield1="0"/>
  <class id="*2" name="A1" short="A1" teacherid="" classroomids="" grade="" customfield1="30"/>
  <class id="*3" name="A2" short="A2" teacherid="" classroomids="" grade="" customfield1=""/>
</classes>

I want to check that the id attribute is unique.


Solution

  • You can use a HashSet to check for uniqueness.

    var set = new HashSet<string>();
    foreach(var id in doc.Descendants()
                     .Select(a => a.Attribute("id").Value))
      if(!set.Add(id))
        throw new Exception("Not Unique");