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
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;
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.