Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 665
vicky Avatar asked Mar 06 '26 04:03

vicky


1 Answers

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

like image 195
Giorgos Betsos Avatar answered Mar 08 '26 19:03

Giorgos Betsos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!