我希望bcl.DateTime元素在XPathDocument中转换为xs:dateTime
这可能与第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>发布于 2011-08-10 09:18:30
有趣;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属性向xs公开一个孪生DateTime值,或者(也许更好)使用单独的DTO来表示.proto/ xs方面并在它们之间映射。.proto不会喜欢跨平台的bcl.DateTime。
https://stackoverflow.com/questions/6994901
复制相似问题