我想要bcl。DateTime元素转换为xs: DateTime在XPathDocument
这可能与问题#69有关
我创建了一个像这样的小测试项目
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())
{
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();
}
}
}
}
它创建以下XML文件:
<?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>
有趣;bcl.DateTime
类型实际上是为了表示内部的DateTime
格式,而不是为了直接使用。我可能应该纠正这一点,以便在翻译期间将bcl.DateTime
解释为DateTime
,但是这里更典型的用法(因为您正在谈论. net类型,例如DateTime
)将是代码优先的,即
[ProtoContract]
class Test {
[ProtoMember(1, IsRequired = true)]
public DateTime AsOf {get;set;}
}
这应该可以在protobuf和xs的目的下正常工作。
这里需要。proto吗?我可以修补,我只是想知道是否需要。
重新注释/更新,并重新使用。proto -我强烈建议使用最基本的通用时间值格式-可能是long
(或string
),并且或者在部分类中使用shim属性将两个DateTime
值暴露给xs,或者(也许更好)使用单独的DTO来表示protobuf/xs方面并在它们之间映射。.proto不会喜欢平台间的bcl.DateTime
。