Ben Junior
Ben Junior

Reputation: 2589

How to check if a value already exists in an xml file using linq

Although there are many answers to this topic, I couldn't find one that worked in my case. The app opens the xml file to add new entries from a list, but prevents duplicates. I don't know how to check (using Linq) if the item is already in the xml

<!-- XML File sample -->
<?xml version="1.0" encoding="UTF-8"?>
<Items>
 <Item>
    <Text>AUDI</Text>
  </Item>
<Item>
  <Text>BMW</Text>
</Item>
</Items>

and this is the code. (I left out trim, uppercase, etc for simplicity) The problem is in the result var, it always return false.

XDocument doc = XDocument.Load(@filePath);
for (int i = 0; i < items.Count; i++)
  {
     var result = doc.Descendants("Item").Any(x => x.Element("Text").ToString().Equals(items[i]);

     if (! result)
          {

          }

doc.Save(@filePath);

Upvotes: 0

Views: 1273

Answers (2)

evanmcdonnal
evanmcdonnal

Reputation: 48114

I believe you're misinterpreting the format of your XML.. You're looking to match the InnerXml of the Text element which you never do here. So you need to move from Root -> Items -> Item -> Text -> Value which isn't exactly what's happening with your code.

So at a minimum you need to use the Value reference on the Text element (x.Element("Text").Value). Also, I think your call to Descendants directly returns the Text elements so I would recommend inspecting the IEnum after that and confirming what level of the xml you're at at that point. I haven't used that method but my understanding is that it gives you descendants of the xpath you provide which means it gives you Text elements. If that is the case change that string to "Items" and you'll be good to go.

Upvotes: 2

C1rdec
C1rdec

Reputation: 1687

Your problem is :

x.Element("Text").ToString()

To get the string inside the Text node use .Value

Like so:

XDocument doc = XDocument.Load(@filePath);
for (int i = 0; i < items.Count; i++)
{
    var result = doc.Descendants("Item").Any(x => x.Element("Text").Value.Equals(items[i]));

    if (!result)
    {

    }
}

doc.Save(@filePath);

Upvotes: 2

Related Questions