protobuf-net: bcl.DateTime to xs:dateTime?
I would like bcl.DateTime elements to be converted to xs:dateTime in XPathDocument
This might be related to issue #69
I created a small test project like this
test.proto
import "bcl.proto";
message Test {
required bcl.DateTime tAsOf = 1;
}
program.cs
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using ProtoBuf;
using test;
namespace DateTimeXML
{
class Program
{
static void Main()
{
var d = new bcl.DateTime() {value = new DateTime(2011, 7, 31).Ticks};
var t = new Test() {tAsOf = d};
var xml = Serialize(t);
WriteXpathDocument(xml, "c:\\temp\\xpathdoc.xml");
}
private static XPathDocument Serialize(Test obj)
{
XPathDocument xmlDoc;
Serializer.PrepareSerializer<Test>();
var x = new XmlSerializer(obj.GetType());
using (var memoryStream = new MemoryStream())
开发者_如何学JAVA {
using (TextWriter w = new StreamWriter(memoryStream))
{
x.Serialize(w, obj);
memoryStream.Position = 0;
xmlDoc = new XPathDocument(memoryStream);
}
}
return xmlDoc;
}
private static void WriteXpathDocument(XPathDocument xpathDoc, string filename)
{
// Create XpathNaviagtor instances from XpathDoc instance.
var objXPathNav = xpathDoc.CreateNavigator();
// Create XmlWriter settings instance.
var objXmlWriterSettings = new XmlWriterSettings();
objXmlWriterSettings.Indent = true;
// Create disposable XmlWriter and write XML to file.
using (var objXmlWriter = XmlWriter.Create(filename, objXmlWriterSettings))
{
objXPathNav.WriteSubtree(objXmlWriter);
objXmlWriter.Close();
}
}
}
}
it creates the following xml file:
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<tAsOf>
<value>634476672000000000</value>
</tAsOf>
</Test>
Interesting; the bcl.DateTime
type is really intended to represent the internal DateTime
format, and is not really intended for use directly. I should probably correct that to interpret bcl.DateTime
as DateTime
during translation, but the more typical usage here (since you are talking about .NET types, such as DateTime
) would be code-first, i.e.
[ProtoContract]
class Test {
[ProtoMember(1, IsRequired = true)]
public DateTime AsOf {get;set;}
}
this should then work as desired for both protobuf and xs purposes.
Do you need .proto here? I can patch that, I just want to know if it is required.
Re the comment / update, and re using .proto - I would strongly suggest using the most basic common format for the time value - possibly a long
(or a string
maybe), and either use shim properties in a partial class to expose a twin DateTime
value to xs, or (perhaps better) use a separate DTO to represent the protobuf / xs aspects and map between them. A .proto isn't going to love bcl.DateTime
between platforms.
精彩评论