2011-01-17 5 views
5

나는 내가 그 사용자 정의 데이터 형식을 가진 요소가 제어하지 않는 XML 문서를역 직렬화 사용자 지정 XML 데이터 형식

<foo> 
    <time type="epoch_seconds">1295027809.26896</time> 
</foo> 

내가 자동으로 에포크 초에 변환 할 수있는 클래스를 가지고 싶다 :

[Serializable] 
public class Foo 
{ 
     public Foo() 
     { 
     } 

     public EpochTime Time { get; set; } 
} 

는 XML 시리얼 라이저는 type="epoch_time"와 XML을 찾을 때 사용하는 알 수 있도록 EpochTime 클래스를 정의 할 수있는 방법이 있습니까? 그렇다면 WriteXmlReadXml을 어떻게 설정합니까?

+0

('[Serializable]'은 xml serialization에 영향을 미침) –

답변

4

일반적인 방법은 단순히 예상대로 동작 속성과를 심은 것입니다 여기에


[XmlElement("time")] 
public EpochTime Time { get; set; } 
가와 완벽한 예입니다 당신의 xml :

using System; 
using System.IO; 
using System.Xml; 
using System.Xml.Serialization; 
static class Program 
{ 
    static void Main() 
    { 
     Foo foo; 
     var ser = new XmlSerializer(typeof(Foo)); 
     using (var reader = XmlReader.Create(new StringReader(@"<foo> 
    <time type=""epoch_seconds"">1295027809.26896</time> 
</foo>"))) 
     { 
      foo = (Foo)ser.Deserialize(reader); 
     } 
    } 
} 
public class EpochTime 
{ 
    public enum TimeType 
    { 
     [XmlEnum("epoch_seconds")] 
     Seconds 
    } 
    [XmlAttribute("type")] 
    public TimeType Type { get; set; } 
    [XmlText] 
    public string Text { get; set; } 
    private static readonly DateTime Epoch = new DateTime(1970, 1, 1); 
    [XmlIgnore] public DateTime Value 
    { 
     get 
     { 
      switch (Type) 
      { 
       case TimeType.Seconds: 
        return Epoch + TimeSpan.FromSeconds(double.Parse(Text)); 
       default: 
        throw new NotSupportedException(); 
      } 
     } 
     set { 
      switch (Type) 
      { 
       case TimeType.Seconds: 
        Text = (value - Epoch).TotalSeconds.ToString(); 
        break; 
       default: 
        throw new NotSupportedException(); 
      } 
     } 
    } 
} 
[XmlRoot("foo")] 
public class Foo 
{ 
    public Foo() 
    { 
    } 

    [XmlElement("time")] 
    public EpochTime Time { get; set; } 
} 
0

ISerializable을 구현해야합니까? 다음은 시나리오에서 작동 할 수 있습니다 :

public class EpochTime 
{ 
    [XmlText] 
    public double Data { get; set; } 
    [XmlAttribute("type")] 
    public string Type { get; set; } 
} 

public class Foo 
{ 
    public EpochTime Time { get; set; } 
} 

class Program 
{ 
    public static void Main() 
    { 
     var foo = new Foo 
     { 
      Time = new EpochTime 
      { 
       Data = 1295027809.26896, 
       Type = "epoch_seconds" 
      } 
     }; 
     var serializer = new XmlSerializer(foo.GetType()); 
     serializer.Serialize(Console.Out, foo); 
    } 
} 

또한 [Serializable]XmlSerializer에 영향을주지 않습니다 것을 알 수 있습니다. , 당신이 필요로하는 것 또한

public class EpochTime { 
    public enum TimeType { 
     [XmlEnum("epoch_seconds")] Seconds 
    } 
    [XmlAttribute("type")] public TimeType Type {get;set;} 
    [XmlText] public string Text {get;set;} 

    [XmlIgnore] public DateTime Value { 
     get { /* your parse here */ } 
     set { /* your format here */ } 
    } 
} 

을 :