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

#1 Cookers  Icon 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

<food>
	<cookies>0</cookies>
</food>


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  Icon 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.

Linq:
http://msdn.microsof...y/bb387061.aspx

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



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

#3 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3650
  • View blog
  • Posts: 11,420
  • 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.
http://msdn.microsof...y/182eeyhh.aspx
Was This Post Helpful? 1
  • +
  • -

#4 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1525
  • View blog
  • Posts: 5,961
  • 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..

[XmlRoot(ElementName="food")]
public class Food
{
    [XmlElement(ElementName="cookies")]
    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