代码之家  ›  专栏  ›  技术社区  ›  Jonathan C Dickinson

直接向XML Linq反序列化/从XML Linq反序列化

  •  22
  • Jonathan C Dickinson  · 技术社区  · 17 年前

    是否有任何方法可以在不往返XmlDocument/temp字符串的情况下反序列化/序列化对象?我正在寻找以下内容:

    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = new XDocument();
            MyClass c = new MyClass();
            c.SomeValue = "bar";
    
            doc.Add(c);
    
            Console.Write(doc.ToString());
            Console.ReadLine();
        }
    }
    
    [XmlRoot(ElementName="test")]
    public class MyClass
    {
        [XmlElement(ElementName = "someValue")]
        public string SomeValue { get; set; }
    }
    

    我 做 有自动反序列化/序列化的扩展方法,但这不是我想要的(这是客户端的,但我仍然想要更优化的)。

    1 回复  |  直到 17 年前
        1
  •  34
  •   Amy B    17 年前

    this ?

        public XDocument Serialize<T>(T source)
        {
            XDocument target = new XDocument();
            XmlSerializer s = new XmlSerializer(typeof(T));
            System.Xml.XmlWriter writer = target.CreateWriter();
            s.Serialize(writer, source);
            writer.Close();
            return target;
        }
    
        public void Test1()
        {
            MyClass c = new MyClass() { SomeValue = "bar" };
            XDocument doc = Serialize<MyClass>(c);
            Console.WriteLine(doc.ToString());
        }