question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked Viorel-1 commented

LINQ Find and replace exact match data in xml file

i am finding and replacing data in xml now by linq this way

 XDocument xmlDoc = XDocument.Load(files);
    
                             var items = (from item in xmlDoc.Descendants("TickerBrokerStandardDateLineitemValue")
                                          where item.Element("TabName").Value.Trim().ToUpper() == olditem.Trim().ToUpper()
                                          select item).ToList();
    
                             foreach (var item in items)
                             {
                                 item.Element("TabName").SetValue(newitem);
                             }
                             xmlDoc.Save(files);

it is working but the problem is if there few values for TabName field looks bit similar then those data also updating.

see two data for TabName
1) Net Revenue
1) Net Revenue Consolidated

so when i will replace only Net Revenue then Net Revenue Consolidated is also updated which i do not want. i want to search by exact tabname value and replace that exact data not other similar data.

how to achieve it with LINQ?

i found one link but not sure does it solve my purpose @AngelinaJoli second answer
https://forums.asp.net/t/2124481.aspx?LINQ+How+to+Check+only+matching+string+based+on+conditions+in+LINQ+Query

please share a code example. thanks


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Viorel-1 commented

Try this code:

 var items = from item in xmlDoc.Descendants("TickerBrokerStandardDateLineitemValue").Elements("TabName")
    where item.Value.Trim().ToUpper() == olditem.Trim().ToUpper()
    select item;
        
 foreach (var item in items)
 {
    item.SetValue(newitem);
 }
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

ok i will try but you did not use ToList() at end like

  var items = (from item in xmlDoc.Descendants("TickerBrokerStandardDateLineitemValue").Elements("TabName")
     where item.Value.Trim().ToUpper() == olditem.Trim().ToUpper()
     select item).ToList();

if i construct this way then any problem will occur....please suggest. thanks

0 Votes 0 ·

I think that if you need a list of found items (for processing later, multiple times, for example) then use .ToList. To traverse the document one time using your foreach loop, .ToList can be used too, but it is not necessary.

0 Votes 0 ·