Reputation: 999
<ENVELOPE>
<BODY>
<IMPORTDATA>
<REQUESTDATA>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="4b6b9384" VCHKEY="4b6b9384" VCHTYPE="Payment" ACTION="Create" OBJVIEW="Accounting Voucher View">
<DATE>20160102</DATE>
</VOUCHER>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>
this is the xml file,Now I want to serialize date into .net as like 01/02/2016(dd/mm/yy or mm/dd/yy format) I tried this two way
objCompanyVouchar.VOUCHER_DATE=XmlConvert.ToDateTime(node.SelectSingleNode("DATE").InnerText)
objCompanyVouchar.VOUCHER_DATE = Convert.ToDateTime(node.SelectSingleNode("DATE").InnerText);
But it show the exception "String was not recognized as a valid DateTime." Do anyone knows how can I solve this?
Upvotes: 3
Views: 839
Reputation: 34421
Try xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var inportData = doc.Descendants("IMPORTDATA").Select(x => new {
reportName = (string)x.Descendants("REPORTNAME").FirstOrDefault(),
company = (string)x.Descendants("SVCURRENTCOMPANY").FirstOrDefault(),
remoteID = (string)x.Descendants("VOUCHER").FirstOrDefault().Attribute("REMOTEID"),
vchKey = (string)x.Descendants("VOUCHER").FirstOrDefault().Attribute("VCHKEY"),
date = DateTime.ParseExact((string)x.Descendants("DATE").FirstOrDefault(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
voucherName = (string)x.Descendants("VOUCHERTYPENAME").FirstOrDefault(),
voucherNumber = (int)x.Descendants("VOUCHERNUMBER").FirstOrDefault(),
ledgerName = (string)x.Descendants("PARTYLEDGERNAME").FirstOrDefault()
}).FirstOrDefault();
}
}
}
Upvotes: 0
Reputation: 1
using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;
namespace XMLTest1
{
public class Test
{
public String value1;
public String value2;
}
class listtest
{
static void Main(string[] args)
{
XmlDocument myXml = new XmlDocument();
XPathNavigator xNav = myXml.CreateNavigator();
Test myTest = new Test() { value1 = "Value 1", value2 = "Value 2" };
XmlSerializer x = new XmlSerializer(myTest.GetType());
using (var xs = xNav.AppendChild())
{
x.Serialize(xs, myTest);
}
Console.WriteLine(myXml.OuterXml);
Console.ReadKey();
}
} }
Upvotes: 0
Reputation: 3239
Nothing need to do with XmlConvert
or required for Convert
class.
Let's say you know the format is "yyyyMMdd", then what you need to do is:
var date= DateTime.ParseExact(node.SelectSingleNode("DATE").InnerText,"yyyyMMdd", CultureInfo.InvariantCulture);
objCompanyVouchar.VOUCHER_DATE= date; //If VOUCHER_DATE is DateTime
//objCompanyVouchar.VOUCHER_DATE = date.ToString(); //If VOUCHER_DATE is String
| you can choose the format you want, read more at ToString()
Upvotes: 4