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

2.2k views Asked by At

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!

3

There are 3 answers

3
Jonesopolis On BEST ANSWER

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

0
Martin Milan On

Elements() only looks at a single level in the heirarchy. I think you want Descendants() instead...

0
Rhumborl On

If you want an older-school XPath option, you need to do a global search on the tree - you can use the // XPath expression for this:

var els = rootElRecDocXml.SelectNodes("//[text()='"+mFilePath+"']");