Click here to Skip to main content
15,868,056 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am newly working with XML files with C#, currently I am facing a problem about editing a specific value from XML file.
Let's say I have this XML file (plist.xml) :


XML
<Project>
  <ProjectDetail id="1">
    <Title>Dominic Crossroad</Title>
    <Platform>Android</Platform>
    <GGI>1522</GGI>
    <DBNAME>dominicroad</DBNAME>
    <GVERSION>1.0.0, 1.2.0i, 2.0.0j</GVERSION>
  </ProjectDetail>
  <ProjectDetail id="2">
    <Title>Kungfu Master</Title>
    <Platform>UNIX</Platform>
    <GGI>1523</GGI>
    <DBNAME>kfmaster</DBNAME>
    <GVERSION>1.0.0, 2.3.0d</GVERSION>
  </ProjectDetail>
</Project>


What I want to is to edit <gversion> node from specific part.
On above sample, Title = kungfu master have two version (1.0.0 and 2.3.0d).
I want to add new version (3.0.0a), so the <gversion> for Kungfu Master will be like:

XML
<GVERSION>1.0.0, 2.3.0d, 3.0.0a</GVERSION>


Anyone can give me example for it?

What I have tried:

I googled a lot of sources, but I am confused where to start because this is my first work with XML files.
Posted
Updated 24-Feb-16 22:44pm

1 solution

Try with below code:
C#
string xmlData = @"<project>
		  <projectdetail id="1">
			<Title>Dominic Crossroad</Title>
			<platform>Android</platform>
			<ggi>1522</ggi>
			<dbname>dominicroad</dbname>
			<gversion>1.0.0, 1.2.0i, 2.0.0j</gversion>
		  </projectdetail>
		  <projectdetail id="2">
			<Title>Kungfu Master</Title>
			<platform>UNIX</platform>
			<ggi>1523</ggi>
			<dbname>kfmaster</dbname>
			<gversion>1.0.0, 2.3.0d</gversion>
		  </projectdetail>
		</project>";
	
// Parsing XML string
XDocument doc = XDocument.Parse(xmlData);

// Filtering the project node which has title Kungfu
XElement projectObject = doc.Descendants("ProjectDetail").Where(rec => (string)rec.Element("Title").Value == "Kungfu Master").SingleOrDefault();

if(projectObject != null)
{
	projectObject.Element("GVERSION").SetValue(projectObject.Element("GVERSION").Value + ", 3.0.0a");
}

string test = doc.ToString(); // Update XML string
doc.Save("path"); // save your updated XML
 
Share this answer
 
v2
Comments
satrio_budidharmawan 26-Feb-16 2:30am    
Works like charms,
Thank you,
:)
[no name] 26-Feb-16 3:56am    
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