Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Xquery Xml document thru C#

Posted on 2011-02-27
18
914 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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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
 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

839 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