c# – 自定义DateTime XML序列化

我希望能够使用不是服务器的特定时区序列化DateTime,也不是客户端时间.基本上,任何时区.

是否可以在.Net2.0 webservices中覆盖DateTime序列化?

我使用xsd.exe编译xmlschema,所以我尝试使用XmlSchemaImporter.

OnSerialize示例显示值更改,但不更改输出格式.

XmlSchemaImporter,将其加载到gac中,运行xsd.exe,并生成具有我想要的类的代码……但该类是一个属性,最终无法反映.

[InvalidOperationException: Cannot
serialize member ‘metadataDateTime’ of
type Cuahsi.XmlOverrides.W3CDateTime.
XmlAttribute/XmlText cannot be used to
encode complex types.]

生成的代码

[System.Xml.Serialization.XmlAttributeAttribute()]
public Cuahsi.XmlOverrides.W3CDateTime dateTime {
    get {
        return this.dateTimeField;
    }
    set {
        this.dateTimeField = value;
    }
}

XmlSchemaImporter

public class ImportW3CTime : 
  System.Xml.Serialization.Advanced.SchemaImporterExtension
{
    public override string ImportSchemaType(string name, string ns,
        XmlSchemaObject context, XmlSchemas schemas,
        XmlSchemaImporter importer, CodeCompileUnit compileUnit, 
        CodeNamespace mainNamespace, CodeGenerationOptions options,
        CodeDomProvider codeProvider)
    {
        if (XmlSchema.Namespace == ns)
        {
            switch (name)
            {
                case "dateTime":
                    string codeTypeName = typeof(W3CDateTime).FullName;
                    CodeTypeDeclaration cls = 
                        new CodeTypeDeclaration("W3CDateTime");                     
                    cls.IsStruct = true;
                    cls.Attributes = MemberAttributes.Public;
                    cls.BaseTypes.Add("dateTime");
                    mainNamespace.Types.Add(cls);
                    return codeTypeName;
                default: return null;
            }
        }
        else { return null; }
    }
}

附录1:
我只是厌倦了DateTimeoffset,当类被标记为时仍然会导致错误:

[System.Xml.Serialization.XmlAttributeAttribute(DataType = "dateTime")]
public System.DateTimeOffset metadataDateTime {
    get {
        return this.metadataDateTimeField;
    }
    set {
        this.metadataDateTimeField = value;
    }
}

最佳答案 不要直接序列化DateTimeOffset,而是序列化字符串:

// Don't serialize this one
[System.Xml.Serialization.XmlIgnore]
public System.DateTimeOffset metadataDateTime
{
    get { ... }
    set { ... }
}


// Serialize this one instead
[System.Xml.Serialization.XmlAttribute("metadataDateTime")]
public string metadataDateTimeXml
{
    get { /* format metadataDateTime to custom format */ }
    set { /* parse metadataDateTime from custom format */ }
}
点赞