-1

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!

StepUp
  • 36,391
  • 15
  • 88
  • 148

3 Answers3

6

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

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • 2
    you should note that this changes won't affect actual document unless you save it. – Selman Genç Nov 25 '14 at 13:31
  • @Selman22 why on Earth would you have to tell a person that. `Please note that anything will not be saved unless you save it`.... Duh? – DidIReallyWriteThat Nov 25 '14 at 13:56
  • 3
    because it is true. someone who didn't use Linq to XML before could easily think this will affect the document itself. apperantely you haven't seen enough question here otherwise you would get my point. – Selman Genç Nov 25 '14 at 14:00
1

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

Martin Milan
  • 6,346
  • 2
  • 32
  • 44
1

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+"']");
Rhumborl
  • 16,349
  • 4
  • 39
  • 45