vicky vicky - 11 months ago 55
ASP.NET (C#) Question

Avoid duplicate entry in xml file c#

I am trying to restrict duplicate entry to an XML file and below is the XML file.

<?xml version="1.0" standalone="yes"?>

Now if I try to add Ryan or Danny again to the ID I should alert like user name already exists.

I'm using the below code and it doesn't work.
is a string and has username value to be added. Can anyone provide suggestions?

XDocument xDoc = XDocument.Load(Server.MapPath("~/Info.xml"));
bool userExistsAlready = xDoc.Descendants("Details").Any(x => (string)x.Attribute("ID") == strName);
if (userExistsAlready)

Answer Source

Try this way:

bool userExistsAlready = xDoc.Descendants("Details")
                             .Any(x => x.Value == "Ryan");

The problem with your code is that it tries to access attribute ID. But ID is in fact another XML element contained inside element <Details>.