0

I have the XML in the below form.

<TxLife>
  <Policy>
    <PolNumber>BB1062632</PolNumber>
    <FirstName>EWAN</FirstName>
    <LastName>MCKENZIE</LastName>
    <BirthDate>1972-03-08</BirthDate>
    <MailType>ABC</MailType>
  </Policy>
  <Policy>
    <PolNumber>BB1234567</PolNumber>
    <FirstName>TEST</FirstName>
    <LastName>ONE</LastName>
    <BirthDate>1972-03-08</BirthDate>
    <MailType>DEF</MailType>
 </Policy>
</TxLife>

I have written the code to fetch the value in string array with the below code:

 string[] arr = doc.Descendants("PolNumber").Select(element => element.Value).ToArray();

But not sure how to get individual values and store in variable

rene
  • 41,474
  • 78
  • 114
  • 152
Kavy
  • 1
  • 1

2 Answers2

0

Option 1 : Deserialization

Instead of using Linq To XML, you could deserialize your object and store the values.

var serializer = new XmlSerializer(typeof(TxLife));
using (TextReader reader = new StringReader(strXml))
{
    var result = (TxLife)serializer.Deserialize(reader);
}

Where TxLife is defined as

[XmlRoot(ElementName="Policy")]
public class Policy 
{
    [XmlElement(ElementName="PolNumber")]
    public string PolNumber { get; set; }
    [XmlElement(ElementName="FirstName")]
    public string FirstName { get; set; }
    [XmlElement(ElementName="LastName")]
    public string LastName { get; set; }
    [XmlElement(ElementName="BirthDate")]
    public string BirthDate { get; set; }
    [XmlElement(ElementName="MailType")]
    public string MailType { get; set; }
}

[XmlRoot(ElementName="TxLife")]
public class TxLife {
    [XmlElement(ElementName="Policy")]
    public List<Policy> Policy { get; set; }
}

Option 2 : Linq To Xml

In case you want to stick to Linq To Xml, You can use

var root = XElement.Parse(strXml);
var policies = new List<Policy>();
foreach(var item in root.Descendants("Policy"))
{
    policies.Add(new Policy
    {
     PolNumber= item.Element("PolNumber").Value,
     FirstName = item.Element("FirstName").Value,
     LastName = item.Element("LastName").Value,
     BirthDate = item.Element("BirthDate").Value,
      MailType = item.Element("MailType").Value
    });
}
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
0

Rather than use Anu solution with for loop, use just linq with select which is more efficient. Also value can give issue when element does not exist so cast to string is better. See code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string connStr = "Enter your connection string here";
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "WB_SetNotification";  //stored procdure name

            SqlParameter policyNumber = cmd.Parameters.Add(new SqlParameter("@PolicyNumber", SqlDbType.VarChar, 20));
            cmd.Parameters.Add(policyNumber);
            cmd.Parameters["@PolicyNumber"].Direction = ParameterDirection.Input;

            SqlParameter firstName = cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.VarChar, 50));
            cmd.Parameters.Add(firstName);
            cmd.Parameters["@FirstName"].Direction = ParameterDirection.Input;

             SqlParameter lastName = cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.VarChar, 50));
            cmd.Parameters.Add(lastName);
            cmd.Parameters["@LastName"].Direction = ParameterDirection.Input;

            SqlParameter dob = cmd.Parameters.Add(new SqlParameter("@DateOfBirth", SqlDbType.DateTime));
            cmd.Parameters.Add(dob);
            cmd.Parameters["@DateOfBirth"].Direction = ParameterDirection.Input;

            XDocument doc = XDocument.Load(FILENAME);

            List<Policy> policies = doc.Descendants("Policy").Select(item => new Policy()
            {
                PolNumber = (string)item.Element("PolNumber"),
                FirstName = (string)item.Element("FirstName"),
                LastName = (string)item.Element("LastName"),
                BirthDate = (string)item.Element("BirthDate"),
                MailType = (string)item.Element("MailType")
            }).ToList();

            foreach (Policy policy in policies)
            {
                cmd.Parameters["@PolicyNumber"].Value  = policy.PolNumber;
                cmd.Parameters["@FirstName"].Value = policy.FirstName;
                cmd.Parameters["@LastName"].Value = policy.LastName;
                cmd.Parameters["@DateOfBirth"].Value = policy.BirthDate;

                cmd.ExecuteNonQuery();
            }


        }
        public class Policy
        {
            public string PolNumber { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string BirthDate { get; set; }
            public string MailType { get; set; }
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Hi, I used the same code.it is retrieving the data in the variale. Now if i want to use the varaibles to be used to save the data in DataBase. How can i do it. – Kavy Dec 25 '18 at 11:19
  • You need to be more specific. What type of database? What are the table names and columns? – jdweng Dec 25 '18 at 11:49
  • i am sorry. i have to send to store procedure by calling it after this list. – Kavy Dec 25 '18 at 11:56
  • .[WB_SetNotification] CompanyNumber varchar(3), PolicyNumber varchar(20), DocumentType varchar(6), MailType varchar(15), DocID numeric(9), -- Needed by IMS PreAssignNTUserName varchar(50) = '', FirstName varchar(50), LastName varchar(50), DateOfBirth datetime, NotificationIDPointer – Kavy Dec 25 '18 at 11:59
  • See msdn : https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.beginexecutenonquery?view=netframework-4.7.2 Example uses UPDATE query and you need to replace with an INSERT query. Also for Synchronous : https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executenonquery?view=netframework-4.7.2 – jdweng Dec 25 '18 at 12:05
  • I updated code to add write statements to database. Not sure of stored procedure names and parameters. Took best guess. – jdweng Dec 25 '18 at 12:43
  • HI, This looks fine. I had one more question like if i need to add hard coded values, as i have many paramters apart from these 4 already defined. How can i achieve that.. Sorry i am new to this, hence asking too many questions. – Kavy Dec 26 '18 at 04:00
  • i am getting the error as below :The SqlParameter is already contained by another SqlParameterCollection. – Kavy Dec 26 '18 at 06:30
  • Error is resolved. I used only the second part of the code with cmd.parameters.addwith values method. Now i have to log the error in log file. How can i check if the sql parameter value being passed is NULL? – Kavy Dec 26 '18 at 09:02
  • You can write additional fields to the database in the for loop : cmd.Parameters["@AnotherParameter"].Value = "Any Value"; You can test for nulls also in the for loop : if(policy.PolNumber == string.Empty) – jdweng Dec 26 '18 at 10:12
  • HI,I need to read data from this kind of XML, can you please suggest. – Kavy Jan 11 '19 at 08:47
  • Can you use Anu solution for DeSerialization? – jdweng Jan 11 '19 at 10:19