views:

55

answers:

1

hi., this is my xml file

<Persons>
  <Person>
    <id>1</id>
    <Name>Ingrid</Name>
  </Person>
  <Person>
    <id>2</id>
    <Name>Ella</Name>
    </Person>
</Persons>

i am using linq xml.

here the id should be auto-generated..

i need to check if the value of node id already exists .

if not exists it should create a new id..how to do this using linq. any pointers?

thank you

+5  A: 
    XDocument doc = XDocument.Parse(xml);

    int id = 1;
    // if you need the element
    XElement ingrid = (from person in doc.Root.Elements("Person")
                       where (int)person.Element("id") == id
                       select person).FirstOrDefault();
    // if you just need to know if it is there
    bool exists = (from person in doc.Root.Elements("Person")
                       where (int)person.Element("id") == id
                       select person).Any();
    // generate a new ID
    int newId = ((from person in doc.Root.Elements("Person")
                  select (int?)person.Element("id")).Max() ?? 0) + 1;
Marc Gravell