【问题标题】:De/Serialize directly To/From XML Linq直接反序列化到/从 XML Linq
【发布时间】:2008-11-24 12:50:35
【问题描述】:

有什么方法可以在不往返 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; }
}

但是,当我这样做时出现错误(不能将非空白字符添加到内容中。)如果我将类包装在元素中,我会看到写入的内容是 ConsoleApplication17.MyClass -所以这个错误是有道理的。

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

有什么想法吗?

【问题讨论】:

    标签: c# xml linq xml-serialization


    【解决方案1】:

    类似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());
        }
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 2012-04-18
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多