"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

April 29, 2012

C# - Notes - Working in XML in C# - Part X Tool Developer Notes

[Previous Post in Series - C# Basics - Tool Developer Notes - Part IX]


Tip #1 - This post is based on reading and updating XML data in C#. Example - Assume you have input as below xml file


Expected ouptut is to populate Sale value based on UnitPrice and Quantity

Steps include
  • Parse the XML
  • Update SaleValue based on Unit Price and Quantity
  • Save the XML file
C# Example code (Console Application)
using System;
using System.Linq;
using System.Data;
using System.Xml.Linq;
namespace xmlExample
{
    class Program
    {
        static void Main(string[] args)
        {
            UpdateSaleValue();
        }
        public static string UpdateSaleValue()
        {
            try
            {
                XDocument xmlFile = XDocument.Load("E:\\SaleData.xml");
                var query = from SaleDataNode in xmlFile.Elements("Sales").Elements("SaleData")
               select SaleDataNode;
                foreach (XElement IndividualSaleData in query)
                {
                    int Quantity = 0;
                    double Price  = 0;
                    double SaleValue = 0;
                    Quantity = Convert.ToInt32(IndividualSaleData.Element("Qty").Value);
                    Price = Convert.ToDouble(IndividualSaleData.Element("UnitPrice").Value);
                    SaleValue = Quantity*Price;
                    IndividualSaleData.Element("SaleValue").Value = SaleValue.ToString();
                 }
                xmlFile.Save("E:\\SaleData.xml");
               return "0";
        }
        catch(Exception Ex)
        {
            return "-1";
        }
    }
}
}

Updated XML results


















Tip #2 - For Error 'The type or namespace name ‘log4net’ could not be found'

Below link was useful to fix the issue

Happy Learning!!!

No comments: