How to Parse XML String
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: How to Parse XML String

  1. #1
    Join Date
    May 2005
    Posts
    6

    How to Parse XML String

    I am using .net 4.0 for my web services (.asmx)

    My client will send following xml string to webservice

    <event>
    <site>FLEX-CUBE</site>
    <eventid>6F98CB30-17DE-48F8-99D9-7660F612ECCB</eventid>
    <eventdata>
    <currencies>
    <currency>
    <isocode>USD</isocode>
    <bankbuyrate>3.65</bankbuyrate>
    <banksellrate>3.695</banksellrate>
    <STAFFbuyrate>3.673</STAFFbuyrate>
    <STAFFsellrate>3.673</STAFFsellrate>
    <displayname>USD</displayname>
    <decimaldigits>4</decimaldigits>
    </currency>
    </currencies>
    </eventdata>
    </event>

    <event>
    <site>FLEX-CUBE</site>
    <eventid>6F98CB30-17DE-48F8-99D9-7660F612ECCB</eventid>
    <eventdata>
    <currencies>
    <currency>
    <isocode>BDT</isocode>
    <bankbuyrate>0.0469</bankbuyrate>
    <banksellrate>0.0484</banksellrate>
    <STAFFbuyrate>0.04742</STAFFbuyrate>
    <STAFFsellrate>0.04742</STAFFsellrate>
    <displayname>BDT</displayname>
    <decimaldigits>4</decimaldigits>
    </currency>
    </currencies>
    </eventdata>
    </event>

    Please let me know how can I parse these values and save it to our local database.

    thanks in advance Junaid

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,182

    Re: How to Parse XML String

    One approach is to not parse and use XmlSerialization (um, actually Deserialization).

    To do this, you create class(es) that represents the xml schema. Then use XmlSerializer to deserialize the xml into an object.

    Finally you read the object's properties and save to the database. The sample below skips the database saving part.

    First, the Event class (which represents a single event xml entry).
    Code:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace CG.EventXmlDeserialization
    {
        [XmlRoot(ElementName = "event", Namespace = "")]
        [XmlType(AnonymousType = true, Namespace = "")]
        public class Event
        {
            public static Event CreateFromXml(string xml)
            {
                var serializer = new XmlSerializer(typeof(Event));
    
                using (var reader = new StringReader(xml))
                {
                    return (Event)serializer.Deserialize(reader);
                }
            }
    
            [XmlElement("site")]
            public string Site { get; set; }
    
            [XmlElement("eventid")]
            public Guid EventId { get; set; }
    
            [XmlElement("eventdata")]
            public EventData Data { get; set; }
    
            public Event()
            {
                Data = new EventData();
            }
        }
    
        public class EventData
        {
            [XmlArray("currencies")]
            [XmlArrayItem("currency")]
            public Currency[] Currencies
            {
                set { if (value != null) { _currencies.AddRange(value); } }
                get { return _currencies.ToArray(); }
            }
    
            public EventData()
            {
                _currencies = new List<Currency>();
            }
    
            private List<Currency> _currencies;
        }
    
        public class Currency
        {
            [XmlElement("isocode")]
            public string IsoCode { get; set; }
            
            [XmlElement("bankbuyrate")]
            public decimal BankBuyRate { get; set; }
            
            [XmlElement("banksellrate")]
            public decimal BankSellRate { get; set; }
            
            [XmlElement("STAFFbuyrate")]
            public decimal StaffBuyRate { get; set; }
            
            [XmlElement("STAFFsellrate")]
            public decimal StaffSellRate { get; set; }
            
            [XmlElement("displayname")]
            public string DisplayName { get; set; }
            
            [XmlElement("decimaldigits")]
            public int DecimalDigits { get; set; }
        }
    }
    Next, code for simulating the incoming event xml, deserializing it into an Event object, and then writing out the properties.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    
    namespace CG.EventXmlDeserialization
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("CG.EventXmlDeserialization");
                Console.WriteLine("Illustrates deserializing xml into an object\n");
                
                // Simulate incoming xml string by reading the xml file
                // and convert it into and xml string
                var xmlDoc = new XmlDocument();
                xmlDoc.Load("event.xml");
                var xml = xmlDoc.InnerXml;
    
                // Deserialize the xml into an Event object
                var evt = Event.CreateFromXml(xml);
    
                // Use the Event object's values
                Console.WriteLine("{0,15} {1}", "EventId:", evt.EventId);
                Console.WriteLine("{0,15} {1}", "Site:", evt.Site);
    
                Console.WriteLine("\n{0,15}", "Currencies:");
                foreach (var currency in evt.Data.Currencies)
                {
                    Console.WriteLine("{0,20} {1}", "IsoCode:", currency.IsoCode);
                    Console.WriteLine("{0,20} {1}", "BankBuyRate:", currency.BankBuyRate);
                    Console.WriteLine("{0,20} {1}", "BankSellRate:", currency.BankSellRate);
                    Console.WriteLine("{0,20} {1}", "StaffBuyRate:", currency.StaffBuyRate);
                    Console.WriteLine("{0,20} {1}", "StaffSellRate:", currency.StaffSellRate);
                    Console.WriteLine("{0,20} {1}", "DisplayName:", currency.DisplayName);
                    Console.WriteLine("{0,20} {1}", "DecimalDigits:", currency.DecimalDigits);
                }
            }
        }
    }
    Sample Output:
    Code:
    CG.EventXmlDeserialization
    Illustrates deserializing xml into an object
    
           EventId: 6f98cb30-17de-48f8-99d9-7660f612eccb
              Site: FLEX-CUBE
    
        Currencies:
                IsoCode: USD
            BankBuyRate: 3.65
           BankSellRate: 3.695
           StaffBuyRate: 3.673
          StaffSellRate: 3.673
            DisplayName: USD
          DecimalDigits: 4
    See attach VS 2012 project
    Attached Files Attached Files

  3. #3
    Join Date
    May 2005
    Posts
    6

    Re: How to Parse XML String

    Thank you so much for your help! it worked perfectly!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center