3

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

1 Answer 1

5
    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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.