Search code examples
c#.netxmlxelement

How to find and change inner text of xml elements? C#


I have a following xml file. I need to change the inner text of ANY tag, which contains the value «Museum», or just a tag for a start:

<src>
   <riga>
      <com>&#190;</com>
      <riquadro797>Direction to move</riquadro797>
   </riga>
   <riga>
      <llt>
         <com>Museum</com>
         <elemento797>Direction not to move</elemento797>
      </llt>
   </riga>
  <operation>
      <com>&#160;</com>
      <riquadro797>Museum</riquadro797>
  </operation> 
  <riga>
    <gt>
        <elemento797>Direction not to move</elemento797>
    </gt>
 </riga>    
</src>

I've parsed this file to XElement. What I've tried and it dos not work:

var tt = xmlCluster.Elements(First(x => x.Value == "Museum");            

This code is not proper, as I cannot predict which element will contain "Museum":

 var el = rootElRecDocXml.SelectSingleNode("src/riga/gt/elemento797[text()='"+mFilePath+"']");

How to do it? Any help will be greatly appreciated!


Solution

  • just grab all elements with Museum values:

     var doc = XDocument.Parse(xml);
     var elements = doc.Descendants().Where(e => e.Value == "Museum");
    
     foreach (var ele in elements)
        ele.Value = "Test";
    
     //doc is updated with new values
    

    as Selman22 noted, doc will just be a working copy of your xml. You'll need to call doc.Save to apply anything back to the disk, or wherever you need