Xquery Xml document thru C#

Hey guru's

Am planning to write a C# class library file to read the XML doc

Eg:

  <?xml version="1.0" encoding="UTF-8" ?>
- <externalPerson_1>
- <!-- Person Level  0
  -->
  <emplId />
  <altEmplId>34534543</altEmplId>
  <birthDate>1978-12-25</birthDate>
  <dlaUserId>david.harrison</dlaUserId>
  <contractor>false</contractor>
- <!--  Contact Details
  -->
 </externalPerson_1>

i wanna store all the fields as an object and call this dll thru windows or console application and update the DB.

Any help much appreciated.
Sha1395Asked:
Who is Participating?
 
Sudhakar PulivarthiProject Lead - EngineeringCommented:
Hi Sha1395

I have written the code for you.. Pls let me know any further enhance u require on it
class Employee
    {
        private string _id;
        private string _alternateId;
        private DateTime? _dateOfBirth;
        private string _userId;
        private bool? _isContractor;


        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }       

        public string AlternateId
        {
            get { return _alternateId; }
            set { _alternateId = value; }
        }        

        public DateTime? DateOfBirth
        {
            get { return _dateOfBirth; }
            set { _dateOfBirth = value; }
        }        

        public string UserId
        {
            get { return _userId; }
            set { _userId = value; }
        }        

        public bool? IsContractor
        {
            get { return _isContractor; }
            set { _isContractor = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (StreamReader reader = new StreamReader("C:\\File.xml"))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(reader.ReadToEnd());

                Employee employee = new Employee();
                string tempString = "";
                DateTime? tempDateTime = null;
                bool? tempBool = null;

                GetNodeValue(xmlDoc.SelectSingleNode("//externalPerson_1/emplId"), ref tempString);
                if (!string.IsNullOrEmpty(tempString))
                {
                    employee.Id = tempString;
                }
                GetNodeValue(xmlDoc.SelectSingleNode("//externalPerson_1/altEmplId"), ref tempString);
                if (!string.IsNullOrEmpty(tempString))
                {
                    employee.AlternateId = tempString;
                }
                GetNodeValue(xmlDoc.SelectSingleNode("//externalPerson_1/birthDate"), ref tempDateTime);
                if (tempDateTime.HasValue)
                {
                    employee.DateOfBirth = tempDateTime.Value;
                }
                else
                {
                    // Set the default for the DOB when not provided.
                }
                GetNodeValue(xmlDoc.SelectSingleNode("//externalPerson_1/dlaUserId"), ref tempString);
                if (!string.IsNullOrEmpty(tempString))
                {
                    employee.UserId = tempString;
                }
                GetNodeValue(xmlDoc.SelectSingleNode("//externalPerson_1/contractor"), ref tempBool);
                if (tempBool.HasValue)
                {
                    employee.IsContractor = tempBool.Value;
                }
                else
                {
                    // Set the default for the contractor when not provided.
                }
            }
        }

        /// <summary>
        /// Gets the XML node value.
        /// </summary>
        /// <param name="node">The node from which the value to be extracted.</param>
        /// <param name="variable">Variable to which the value to be set.</param>
        public static void GetNodeValue(XmlNode node, ref string variable)
        {
            variable = GetNodeValue(node);
        }

        /// <summary>
        /// Gets the XML node value.
        /// </summary>
        /// <param name="node">The node from which the value to be extracted.</param>
        /// <param name="variable">Variable to which the value to be set.</param>
        /// <exception cref="LibException"></exception>
        public static void GetNodeValue(XmlNode node, ref bool? variable)
        {
            string strValue = GetNodeValue(node);

            if (!string.IsNullOrEmpty(strValue))
            {
                try
                {
                    variable = Convert.ToBoolean(strValue);
                }
                catch (FormatException ex)
                {
                    throw new Exception("Invalid bool value " + strValue, ex);
                }
            }
        }

        /// <summary>
        /// Gets the XML node value.
        /// </summary>
        /// <param name="node">The node from which the value to be extracted.</param>
        /// <param name="variable">Variable to which the value to be set.</param>
        /// <exception cref="LibException"></exception>
        public static void GetNodeValue(XmlNode node, ref DateTime? variable)
        {
            string strValue = GetNodeValue(node);

            if (!string.IsNullOrEmpty(strValue))
            {
                try
                {
                    variable = Convert.ToDateTime(strValue);
                }
                catch (FormatException ex)
                {
                    throw new Exception("Invalid datetime value " + strValue, ex);
                }
            }
        }

        /// <summary>
        /// Gets the XML node value.
        /// </summary>
        /// <param name="node">The node from which the value to be extracted.</param>
        /// <returns>The node value</returns>
        private static string GetNodeValue(XmlNode node)
        {
            string strValue = string.Empty;

            if (node != null)
            {
                // Trim the text so that empty string can be checked
                // and avoid unnecessary assignment done
                strValue = node.InnerXml.Trim();
            }

            return (strValue);
        }
    }

Open in new window

0
 
Kalpesh ChhatralaSoftware ConsultantCommented:
0
 
nmarunCommented:
Is it necessary to use XQuery? If not, strongly recommend you to use LINQ - Language INtegrated Query.

http://msdn.microsoft.com/en-us/vcsharp/aa336746

Arun
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
Sha1395Author Commented:
Thans Arun,its not necessary to use XQuery but prefer to use XQuery to extract the objects.
0
 
JaccoCommented:
Hi there.

Hope you mean something like the code I wrote below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace ConsoleApplication1
{
    class Program
    {
        public class Person
        {
            public string altEmplId;
            public DateTime birthDate;
            public string dlaUserId;
            public bool contractor;
        }

        static void Main(string[] args)
        {
            var doc = new XPathDocument("Data.xml");
            XPathNavigator nav = doc.CreateNavigator();
            var expr = nav.Compile("externalPerson_1");
            XPathNodeIterator iterator = nav.Select(expr);
            var Persons = new List<Person>();
            foreach (XPathNavigator person in iterator)
            {
                var p = new Person();
                p.altEmplId = person.SelectSingleNode("altEmplId").Value;
                p.birthDate = person.SelectSingleNode("birthDate").ValueAsDateTime;
                p.dlaUserId = person.SelectSingleNode("dlaUserId").Value;
                p.contractor = person.SelectSingleNode("contractor").ValueAsBoolean;
                Persons.Add(p);
            }
            foreach (var person in Persons)
            {
                // code to store in database
            }
        }
    }
}

Open in new window

0
 
Sha1395Author Commented:
Thanks a lot Sudhakar,i am quite interested to work on XQuery.i will go thru the code and hope if you don't mind if ask any question from the code.
0
 
Sudhakar PulivarthiProject Lead - EngineeringCommented:
Your welcome Sha, We are pleased in helping our experts...
Happy working!!!
0
 
Sha1395Author Commented:
Hi Sudhakar thanks for your earlier help,actually i need one more help.

Scenario is, am getting the external value (thru Webservices) to my system.I have to grab the value from the field and update my Db.

Enclosed my Schema file for your view.

Please give me some advice to proceed

Thanks in Advance
Schema.xsd
0
 
Sudhakar PulivarthiProject Lead - EngineeringCommented:
Hi
>>grab the value from the field - Are u receiving the xml data from the client and want to parse through it and get the field and later update the info to the DB right?
Correct me if i am wrong. Pls Elobrate the input by example with dummy values.
0
 
Sha1395Author Commented:
You are right ,am getting the xml file also (attached here) and grab the value and update the DB.

File.xml
0
 
Sha1395Author Commented:
This is my WSDL file,am totally numb here.

What i suppose to do and how to get the value from webservices. thanks a lot for your help.

I couldn't able to upload my wsdl file with extension,so please change the file extension as wsdl.

Thanks
ImportExportServiceV2.txt
0
 
Sudhakar PulivarthiProject Lead - EngineeringCommented:
Hi,

You have to enhance the Employee object and construct the complete object for each employee details in the xml you received. The parsing for the fields can be done as u can see in the accepeted solution comment post. Once this contruction is done.
Now pass this object to a method which can construct the queries to insert  the data to respective tables.
If u struck in any field parsing from the xml let me know.
Note: Keep ur table structure in mind when ur creating
0
 
Sha1395Author Commented:
Thanks Sudhakar
Even i was trying to use your code in my console application and try to debug its not populate or reading the xml file.

Am quite stuck here.
0
 
Sudhakar PulivarthiProject Lead - EngineeringCommented:
File is on local disk and can open it manually?
0
 
Sha1395Author Commented:
yep the file in C:\File.xml, even i open the file thru Run command

but some how its not reading the file.
0
 
Sha1395Author Commented:
The File.xml (attached in my previous post) is the same file i used to test your code.
0
 
Sha1395Author Commented:
Hi Jacco,

Am extremely sorry i haven't noticed your code until yesterday,it was working really great.Some how i couldn't able to execute Sudhakar code.

your code work like a charm retrieve all the values.i don't know how to share the points...please let me know if you know.

Anyway thanks a ton!
0
 
Sha1395Author Commented:
Hi Sudhakar,

I need some help regarding my webservice ,am trying to pass login info and retrieve the value from my webservice.

But am getting error as well i couldn't able to call a method to pass the string.

You can find the post here : http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_26857377.html

Please give me a help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.