vicky vicky - 1 month ago 9
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"?>
<Info>
<Details>
<ID>Ryan</ID>
</Details>
<Details>
<ID>Danny</ID>
</Details>
</Info>


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.
strName
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)
{
//alert
}

Answer

Try this way:

bool userExistsAlready = xDoc.Descendants("Details")
                             .Elements("ID")
                             .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>.

Comments