protobuf-net:bcl.DateTime到xs:dateTime?

时间:2011-08-09 10:41:32

标签: xml datetime date protobuf-net

我希望在XPathDocument中将bcl.DateTime元素转换为xs:dateTime

这可能与issue #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>

1 个答案:

答案 0 :(得分:0)

有趣; bcl.DateTime类型实际上是为了表示内部DateTime格式,并不是真正意图直接使用。我应该纠正这一点,在翻译过程中将bcl.DateTime解释为DateTime,但这里的更典型的用法(因为你在谈论.NET类型,例如{{1} })将是代码优先的,即

DateTime
然后,这应该按照protobuf和xs目的的要求工作。

你需要.proto吗?我可以补丁一下,我只是想知道是否需要它。


重新评论/更新,并重新使用.proto - 我强烈建议使用最基本的通用格式作为时间值 - 可能是[ProtoContract] class Test { [ProtoMember(1, IsRequired = true)] public DateTime AsOf {get;set;} } (或者long可能),以及< em>要么在部分类中使用shim属性来向xs公开双string值,或者(或许更好)使用单独的DTO来表示protobuf / xs方面并在它们之间进行映射。一个.proto不会喜欢平台之间的DateTime