3 Replies - 683 Views - Last Post: 04 December 2012 - 08:20 AM Rate Topic: -----

#1 Cookers   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 03-December 12

Modifying XML values using C#

Posted 03 December 2012 - 07:39 AM

Hello everyone,

I'm trying to create a program where I can 'log' certain values. For example, I want to know how many cookies I eat each day. The 'total' should read the total amount of cookies I ate and the 'add' should add up x to the total cookies I ate already.

Posted Image


What is the best way to start this? I'm quite a novice when it comes to C# programming, but I felt like this was a good way to learn how to interact with XML files.

Any help is appreciated. Thank you very much in advance.

Is This A Good Question/Topic? 0
  • +

Replies To: Modifying XML values using C#

#2 ipushmycar   User is offline

  • D.I.C Regular

Reputation: 86
  • View blog
  • Posts: 390
  • Joined: 29-August 10

Re: Modifying XML values using C#

Posted 03 December 2012 - 08:00 AM

I normally use XML to pass data between systems or documentation. Like a database to queue to a program that then reads off that queue.

I guess you could use it here.

I would use LINQ to read in the XML. However I suppose you could parse it like a normal text file if you wanted.


Example for like a text file:
foreach (XmlNode node in myXmlDoc.ChildNodes[0].childnodes)

Hopefully that helps.
Was This Post Helpful? 0
  • +
  • -

#3 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 6963
  • View blog
  • Posts: 23,674
  • Joined: 05-May 12

Re: Modifying XML values using C#

Posted 03 December 2012 - 04:27 PM

Just create a class and use XML Serialization. No need to get distracted by writing parsing code.
Was This Post Helpful? 1
  • +
  • -

#4 eclipsed4utoo   User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1536
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Modifying XML values using C#

Posted 04 December 2012 - 08:20 AM

For a simple example like this, you can use LINQ-To-XML...

string xml = "<food><cookies>0</cookies></food>";

XDocument doc = Xdocument.Parse(xml);
int cookies = int.Parse(doc.Root.Element("cookies").Value);

Once it gets more complicated, using XML Serialization will be easier. You could have a food class..

public class Food
    public int Cookies { get; set; }

Then you can use serialization...(I am using my XML generic deserialize method)

//assuming our XML is in a file...
string filePath = @"C:\test\somefile.xml";

Food food = XmlHelper.Deserialize<Food>(filePath);
int cookies = food.Cookies;

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1