1

The project requires to create an XML file. After reading online posts I decided to go with LINQ to XML. (Please keep in mind that I am new to LINQ.) I got stuck at retrieving the data from the DataTable into the XElements.

    protected void XDocument()
{
         XElement FloridaData = new XElement("submitted_file", 
                 from vinList in dt.AsEnumerable()
                 select
                    new XElement("schema_version", "123.45"),
                    new XElement("company",
                    new XElement("company_code",

             new XElement("transaction",              
                    new XElement("transaction_type", vinList.Field<Int32>("transaction_type")),

             new XElement("policy", 
                    new XElement("policy_number", ""),
                    new XElement("policy_effective_date", ""),
                    new XElement("policy_through_date", ""),
                    new XElement("insurance_company_notes", ""),

             new XElement("policy_holder",
                    new XElement("company_indicator", ""),
                    new XElement("first_name", ""),
                    new XElement("middle_name", ""),
                    new XElement("last_name", ""),
                    new XElement("name_suffix", ""),
                    new XElement("gender", ""),
                    new XElement("dob", ""),
                    new XElement("stree_address", ""),
                    new XElement("city", ""),
                    new XElement("state", ""),
                    new XElement("zipcode", ""),
                    new XElement("fl_dln", ""),
                    new XElement("fed_tin", ""),
                    new XElement("non_structured_name", ""),
                    new XElement("ph_transaction_type", ""),
                    new XElement("effective_date", ""),
                    new XElement("fr_case_number", ""),
                    new XElement("fr_certification_date", ""),
                    new XElement("fr_prepared_date", "")),

             new XElement("vehicle",
                    new XElement("fleet_indicator", "read-data"),
                    new XElement("vin", ""),
                    new XElement("year", ""),
                    new XElement("make", ""),
                    new XElement("vehicle_effective_date", ""),
                    new XElement("level_of_coverage", ""),
                    new XElement("vehicle_transaction_type", "")),

             new XElement("verification",
                    new XElement("tracking_number", " "),
                    new XElement("required_coverage_dt", ""),
                    new XElement("status_message", " "),
                    new XElement("days_late", " "),
                    new XElement("yes_confirmed", " "),
                    new XElement("confirmed", " "),
                    new XElement("unconfirmed", " "))
                    )))));


             FloridaData.Save("C:\\Something.xml");
    }

        protected void GetGridViewData()
           {
               SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
               SqlCommand cmd = new SqlCommand();
               cmd.CommandType = CommandType.StoredProcedure;
               cmd.CommandText = "GetFloridaDmvData";
               sqlda = new SqlDataAdapter(cmd);
               cmd.Connection = conn;

               try
               {
                   conn.Open();

                   cmd.Parameters.Add("@RunProcess", SqlDbType.VarChar);
                   cmd.Parameters["@RunProcess"].Value = ddlTransaction.SelectedValue;
                   dt = new DataTable();
                   sqlda.Fill(dt);
                   gvData.DataSource = dt;
                   gvData.DataBind();

                   //IEnumerable<Vehicle> vinList = (IEnumerable<Vehicle>)gvData.DataSource;
               }

               catch (Exception ex)
               {
                   lblMessage.Text = ex.Message;
                   lblMessage.Visible = true;
               }

               finally
               {
                   conn.Close();
                   conn.Dispose();
               }


           }

Stored Procedure is long:

ALTER PROCEDURE [dbo].[GetFloridaDmvData]

(
@RunProcess int
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    --reduce network traffic due to the fact that your client will not receive the message indicating the number of rows affected by a Transact-SQL statement
    SET NOCOUNT ON;
    DECLARE @IFUID AS INT,
        @FileName AS VARCHAR(30),
        @CompCode AS INT,
        @TransSold AS INT,
        @TransInit AS INT,
        @TransAdd AS INT,
        @TransDelete AS INT,
        @FEID AS INT,
        @VehicleTransType AS INT,
        @LevelCov AS VARCHAR(2),
        @LevelCovTruck AS VARCHAR(2),
        @CompIndicator AS VARCHAR(1),
        @Fleet AS VARCHAR(1),
        @FILL AS VARCHAR(5),
        @NR AS INT,
        @Empty AS VARCHAR(7),
        @xml AS NVARCHAR(MAX),
        @TotalCount AS INT,
        @CurrentYear AS VARCHAR(4),
        @PreviousYear AS VARCHAR(4),
        @ExpYear AS VARCHAR(4),
        @FirstPrevDate AS VARCHAR(10),
        @FirstDate AS VARCHAR(10),
        @SecondDate AS VARCHAR(10),
        @ExpDate AS VARCHAR(10),
        @ExpCurrentDate AS VARCHAR(10),
        @TodayDay AS VARCHAR(2),
        @TodayMonth AS VARCHAR(2);

    SET @CurrentYear = YEAR(GETDATE());
    SET @PreviousYear = YEAR(GETDATE()) - 1;
    SET @ExpYear = YEAR(GETDATE()) + 1;
    SET @TodayDay = DAY(GETDATE());
    SET @TodayMonth = MONTH(GETDATE());
    SET @FirstPrevDate = '04/01/' + @PreviousYear;
    SET @FirstDate = '04/01/' + @CurrentYear;
    SET @SecondDate = '12/31/' + @CurrentYear;
    SET @ExpDate = '03/31/' + @ExpYear;
    SET @ExpCurrentDate = '03/31/' + @CurrentYear;
    SET @Empty = '';
    --SET @FileName = 'C:\Repwest2015.xml'
    SET @FileName = 'RepWest' + @TodayMonth + '/' + @TodayDay + '/' + @CurrentYear;
    SET @IFUID = '123';
    SET @CompCode = '13177';
    SET @CompIndicator = 'Y';
    SET @Fleet = 'N';
    SET @FEID = '860274508';
    SET @LevelCov = '02';
    SET @LevelCovTruck = '03';
    SET @TransInit = '20';
    SET @TransSold = '13';
    SET @TransAdd = '31';
    SET @TransDelete = '32';
    SET @FILL = 'something';
    SET @NR = '123';
    SET @TotalCount = (
            SELECT COUNT(*) AS total_count
            FROM Executive_And_SV_Vehicles
            WHERE (Executive_And_SV_Vehicles.STATE = 'FL')
                AND (Executive_And_SV_Vehicles.PRIMARY_DRIVER NOT LIKE '%sold%')
                AND (Executive_And_SV_Vehicles.VERIFIED_THIS_YEAR = 'Y')
            );

    -- Insert statements for procedure here
    SELECT  
    @CompCode AS 'company_code',

    @TransInit AS 'transaction_type',

        CASE 
                                    WHEN GETDATE() < @FirstDate
                                        THEN SV_Policy.Policy + RIGHT(@PreviousYear, 2)
                                    WHEN GETDATE() >= @FirstDate
                                        THEN SV_Policy.Policy + RIGHT(@CurrentYear, 2)
                                    END AS 'policy_number',

                                CASE 
                                    WHEN GETDATE() < @FirstDate
                                        THEN CASE 
                                                WHEN Date_Added >= @FirstPrevDate
                                                    THEN REPLACE(CONVERT(DATETIME, Date_Added, 101), '/', '')
                                                WHEN Date_Added < @FirstPrevDate
                                                    THEN REPLACE(CONVERT(VARCHAR(10), @FirstPrevDate, 101), '/', '')
                                                END
                                    WHEN GETDATE() >= @FirstDate
                                        THEN CASE 
                                                WHEN Date_Added >= @FirstDate
                                                    THEN REPLACE(CONVERT(DATETIME, Date_Added, 101), '/', '')
                                                WHEN Date_Added < @FirstDate
                                                    THEN REPLACE(CONVERT(VARCHAR(10), @FirstDate, 101), '/', '')
                                                END
                                    END AS 'policy_effective_date',

                                CASE 
                                    WHEN GETDATE() < @FirstDate
                                        THEN REPLACE(CONVERT(VARCHAR(10), @ExpCurrentDate, 101), '/', '')
                                    WHEN GETDATE() >= @FirstDate
                                        THEN REPLACE(CONVERT(VARCHAR(10), @ExpDate, 101), '/', '')
                                    END AS 'policy_through_date',

                                @Empty AS 'insurance_company_notes',    



                                        @CompIndicator AS 'company_indicator',
                                        @Empty AS 'first_name',
                                        @Empty AS 'middle_name',
                                        @Empty AS 'last_name',
                                        @Empty AS 'name_suffix',
                                        @Empty AS 'gender',
                                        @Empty AS 'dob',
                                        Executive_And_SV_Vehicles.INSURED_ADDRESS AS 'street_address',
                                        Executive_And_SV_Vehicles.INSURED_CITY AS 'city',
                                        Executive_And_SV_Vehicles.INSURED_STATE AS 'state',
                                        Executive_And_SV_Vehicles.INSURED_ZIPCODE AS 'zipcode',
                                        @Empty AS 'fl_dln',

                                        @FEID AS 'fed_tin',
                                        Executive_And_SV_Vehicles.INSURED_NAME AS 'non_structured_name',

                                                CASE 
                                            WHEN DATE_DELETED IS NOT NULL
                                                AND PRIMARY_DRIVER LIKE '%sold%'
                                                THEN @TransSold
                                            WHEN DATE_DELETED IS NOT NULL
                                                THEN @TransDelete
                                            WHEN GETDATE() >= @FirstDate
                                                THEN @TransInit --@TransAdd 
                                            WHEN GETDATE() < @FirstDate
                                                THEN @TransInit
                                            END AS 'ph_transaction_type',

                                        CASE 
                                            WHEN GETDATE() < @FirstDate
                                                THEN CASE 
                                                        WHEN Date_Added >= @FirstPrevDate
                                                            THEN REPLACE(CONVERT(DATETIME, Date_Added, 101), '/', '')
                                                        WHEN Date_Added < @FirstPrevDate
                                                            THEN REPLACE(CONVERT(VARCHAR(10), @FirstPrevDate, 101), '/', '')
                                                        END
                                            WHEN GETDATE() >= @FirstDate
                                                THEN CASE 
                                                        WHEN Date_Added >= @FirstDate
                                                            THEN REPLACE(CONVERT(DATETIME, Date_Added, 101), '/', '')
                                                        WHEN Date_Added < @FirstDate
                                                            THEN REPLACE(CONVERT(VARCHAR(10), @FirstDate, 101), '/', '')
                                                        END
                                            END AS 'effective_date',

                                        @Empty AS 'fr_case_number',                     
                                        @Empty  AS 'fr_certification_date',                     
                                        @Empty  AS 'fr_prepared_date',


                                @Fleet AS 'FleetIndicator',
                                    Executive_And_SV_Vehicles.VIN AS 'vin',
                                        Executive_And_SV_Vehicles.YEAR AS 'year',
                                        Executive_And_SV_Vehicles.MAKE AS 'make',
                                        REPLACE(CONVERT(DATETIME, Date_Added, 101), '/', '') AS 'vehicle_effective_date',


                                                        CASE 
                                            WHEN PRIMARY_DRIVER LIKE '%U-BOX DELIVERY TRUCK%'
                                                THEN @LevelCovTruck
                                            WHEN PRIMARY_DRIVER NOT LIKE '%U-BOX DELIVERY TRUCK%'
                                                THEN @LevelCov
                                            END AS 'level_of_coverage',
                                                CASE 
                                            WHEN DATE_DELETED IS NOT NULL
                                                AND PRIMARY_DRIVER LIKE '%sold%'
                                                THEN @TransSold
                                            WHEN DATE_DELETED IS NOT NULL
                                                THEN @TransDelete
                                            WHEN GETDATE() >= @FirstDate
                                                THEN @TransInit --@TransAdd 
                                            WHEN GETDATE() < @FirstDate
                                                THEN @TransInit
                                            END AS 'vehicle_transaction_type',
                                            @Empty AS 'tracking_number',
                                        @Empty AS 'required_coverage_date',
                                        @Empty AS 'status_message',
                                        @Empty AS 'days_late',
                                        @Empty AS 'yes_confirmed',
                                        @Empty AS 'confirmed',
                                        @Empty AS 'unconfirmed'


     FROM SV_Policy
            INNER JOIN Executive_And_SV_Vehicles
                ON SV_Policy.ID = Executive_And_SV_Vehicles.SV_Policy
            WHERE (Executive_And_SV_Vehicles.STATE = 'FL')
                AND (Executive_And_SV_Vehicles.PRIMARY_DRIVER NOT LIKE '%sold%')
                AND (Executive_And_SV_Vehicles.VERIFIED_THIS_YEAR = 'Y')
END
Olivera
  • 11
  • 4
  • 1
    just a quick look seems like you are missing a parenthesis or two (close) . . . . I count 11 open and 9 close – Paul Gibson Jan 16 '15 at 22:02
  • Your code in creating an XDocument directly. There's no code here related to a data table. – Steve Mitcham Jan 16 '15 at 22:03
  • Oh it is a long long XML file. Should I post it all? – Olivera Jan 16 '15 at 22:04
  • @Steve That is my problem. I found this code online and thinking to do a similar thing XDocument Employee = new XDocument(new XDeclaration("1.0", "utf-8", "true"), new XElement("COMPNAY", from cust in dt.AsEnumerable() select new XElement("EMPLOYEE", new XElement("NO", cust["EMPLOYEENO"]), new XElement("Remarks", cust["Remarks"]) ))); – Olivera Jan 16 '15 at 22:06
  • What is related to the `DataTable`? Should you retrieve the data from `DataTable` and save in the file in `XML` format? – Hamlet Hakobyan Jan 16 '15 at 22:07
  • Here's a comment on retrieving data from a data table: http://stackoverflow.com/questions/10855/linq-query-on-a-datatable?rq=1 then you can take the output from there and populate your XML. – Steve Mitcham Jan 16 '15 at 22:07
  • Here's another SO on serializing without hardcoding things if you have the code to get a DataTable already http://stackoverflow.com/questions/2244655/how-to-serialize-a-datatable-to-a-string – Steve Mitcham Jan 16 '15 at 22:09
  • @Hamlet Yes. I have a GridView and then I am saving the gridview data to a DataTable because I could't find anywhere how to save the gridview data to my xml file (the one I created) only DataTable to XML. – Olivera Jan 16 '15 at 22:09
  • @Steve I found I think what I need but I am trying to make sense of it: http://stackoverflow.com/questions/9185654/datatable-to-xml-using-linq – Olivera Jan 16 '15 at 22:15
  • You've got quite a bit of nesting. Does your grid view use nested rows to support the sub items? – Steve Mitcham Jan 16 '15 at 22:25
  • I assume, that the `GridView` data have gotten from somewhere. What is the underlying data store for the `GridView`? – Hamlet Hakobyan Jan 16 '15 at 22:31
  • @Steve I bind the gridview using a stored procedure. And after I bind the gridview I put the datasource to the DataTable. Becasue I need to add into the XML file whatever rows the user selects. Is there a way to create a gridview with the nested elements that I need so I can simply export that gridview to xml and not go this long route? – Olivera Jan 16 '15 at 22:34
  • Can you post your stored procedure? – Steve Mitcham Jan 16 '15 at 22:49
  • @Steve I posted both methods. I have been trying to use IEnumerable vinList = (IEnumerable)gvData.DataSource; new XElement("transaction_type", vinList.Field("transaction_type")), – Olivera Jan 16 '15 at 22:57
  • Do you have the SQL? if I can get the structure of the data I can tune the answer you found to show how it can apply here. – Steve Mitcham Jan 16 '15 at 22:59
  • Ok. I've worked out what you are trying and you aren't that far off. I'm writing an answer now – Steve Mitcham Jan 16 '15 at 23:40
  • @Steve OMG you have no idea what a life saver you are. – Olivera Jan 16 '15 at 23:42

2 Answers2

1

Properly formated it currently looks like this

XElement FloridaData =
    new XElement("submitted_file", 
         new XElement("schema_version", "123.45"),
         new XElement("company",
              new XElement("company_code",
                   new XElement("transaction",              
                        new XElement("transaction_type", ""),

                        new XElement("policy", 
                             new XElement("policy_number", ""),
                             new XElement("policy_effective_date", ""),
                             new XElement("policy_through_date", ""),
                             new XElement("insurance_company_notes", "")
                             )
                   )
              );

You aren't closing some of your parenthesis.

Guvante
  • 18,775
  • 1
  • 33
  • 64
  • Thank you I didn't include all the lines from the XML file because is a long one. What I need is to retrieve the data in the XElement: ex: new XElement("test", dt["read the column"]),... but I am sure dt["column"] is not correct – Olivera Jan 16 '15 at 22:12
0

Given your source, you are best generating the XML straight from the DataTable returned from the SqlCommand call. The following method will generate the header information, and then create one XElement for each row in the result. It didn't look like the result set was actually nested based on the SQL in the stored procedure.

Each of the row calls returns an object which is going to cause the XElement output to rely on .ToString() to generate the output, which may not be what you want, but you can substitute a formatting method for the direct call as necessary.

public XDocument GenerateXml(DataTable dt)
{
   XElement floridaData = new XElement ("submitted_file", 
                             new XElement ("schema_version", "123.45"));

   foreach (var row in dt.Rows) {

      var companyRecord = new XElement ("company",
                             new XElement ("company_code", row ["company_code"]),
                             new XElement ("transaction",              
                                new XElement ("transaction_type", row ["transaction_type"]),
                                new XElement ("policy", 
                                   new XElement ("policy_number", row ["policy_number"]),
                                   new XElement ("policy_effective_date", row ["policy_number"]),
                                   new XElement ("policy_through_date", row ["policy_number"]),
                                   new XElement ("insurance_company_notes", row ["policy_number"])
                                )
                             )
                          );
      floridaData.Add (companyRecord);
   }
   return new XDocument (floridaData);
}
Steve Mitcham
  • 5,268
  • 1
  • 28
  • 56