Solved

Xquery Xml document thru C#

Posted on 2011-02-27
18
904 Views
Last Modified: 2012-05-11
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.
0
Comment
Question by:Sha1395
18 Comments
 
LVL 16

Expert Comment

by:Kalpesh Chhatrala
ID: 34994014
0
 
LVL 27

Expert Comment

by:nmarun
ID: 34994198
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
 

Author Comment

by:Sha1395
ID: 34994443
Thans Arun,its not necessary to use XQuery but prefer to use XQuery to extract the objects.
0
 
LVL 11

Accepted Solution

by:
Sudhakar Pulivarthi earned 500 total points
ID: 34994899
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
 
LVL 10

Expert Comment

by:Jacco
ID: 34995017
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
 

Author Comment

by:Sha1395
ID: 34995727
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
 
LVL 11

Expert Comment

by:Sudhakar Pulivarthi
ID: 34995737
Your welcome Sha, We are pleased in helping our experts...
Happy working!!!
0
 

Author Comment

by:Sha1395
ID: 35004258
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
 
LVL 11

Expert Comment

by:Sudhakar Pulivarthi
ID: 35004284
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Sha1395
ID: 35004310
You are right ,am getting the xml file also (attached here) and grab the value and update the DB.

File.xml
0
 

Author Comment

by:Sha1395
ID: 35004333
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
 
LVL 11

Expert Comment

by:Sudhakar Pulivarthi
ID: 35005054
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
 

Author Comment

by:Sha1395
ID: 35005423
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
 
LVL 11

Expert Comment

by:Sudhakar Pulivarthi
ID: 35005520
File is on local disk and can open it manually?
0
 

Author Comment

by:Sha1395
ID: 35005533
yep the file in C:\File.xml, even i open the file thru Run command

but some how its not reading the file.
0
 

Author Comment

by:Sha1395
ID: 35005536
The File.xml (attached in my previous post) is the same file i used to test your code.
0
 

Author Comment

by:Sha1395
ID: 35012212
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
 

Author Comment

by:Sha1395
ID: 35015684
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

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video discusses moving either the default database or any database to a new volume.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now