Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an XML document in which part of it shown below. I want to read and update ‘base’ value of region ‘DEF’ using C#. I need your suggestions. Thanks!

XML
<scenario>
   <world>
      <region name="ABC">
         <demographics>
            <population year="2015">
               <totalPop>6377</totalPop>
            </population>
         </demographics>
         <GDP>
            <base>910</base>
            <force fillout="1" year="1975">0.5</force>
            <labor year="1990">0.02354</labor>
            <Convert constRatio="1">0.96187</Convert>
         </GDP>
      </region>
      <region name="DEF">
         <demographics>
            <population year="2015">
               <totalPop>3363</totalPop>
            </population>
         </demographics>
         <GDP>
            <base>739</base>
            <force fillout="1" year="1975">0.5</force>
            <labor year="1990">0.02354</labor>
            <Convert constRatio="1">0.96187</Convert>
         </GDP>
      </region>

      ....

    </world>
</scenario>
Posted

1 solution

Something like this should work:
C#
//XDocument xdoc = XDocument.Load("fullfielname.xml");
var xNodeToChange = xdoc.Descendants("region")
    .Where(x=>(string)x.Attribute("name") =="DEF")
    .Select(x=>x.Descendants("base"))
    .SingleOrDefault()
    .First();

Console.WriteLine("Original value: {0}", xNodeToChange);
//xNodeToChange is type of XElement
//so we can change it's value ;)
xNodeToChange.Value = "Whatever";
Console.WriteLine("Changed value: {0}", xNodeToChange);
Console.WriteLine();
Console.WriteLine("Document content:");
Console.WriteLine("{0}", xdoc);
//save changes
//xdoc.Save("fullfilename.xml")


For further information, please see: XElement.Value Property[^]
 
Share this answer
 
v4
Comments
getrelax 19-Oct-15 11:48am    
That is good; but you are doing the update on xNodeToChange variable, not on the original document. And xNodeToChange contains only <base>739</base>
Maciej Los 19-Oct-15 11:54am    
It's not true. Debug the programme and check the content of xdoc. base node stores new value.
See updated answer.
getrelax 19-Oct-15 12:32pm    
Yes, you are right. Thanks!
Maciej Los 19-Oct-15 12:44pm    
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900