直接对XML Linq进行反序列化 [英] De/Serialize directly To/From XML Linq

查看:83
本文介绍了直接对XML Linq进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to de/serialize an object without round-tripping a XmlDocument/temp string? I am looking for something like the following:

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; }
}

我这样做的时候会出错(不能将非空格字符添加到内容中.)如果我将类包装在元素中,则会看到写入的内容是< element> ConsoleApplication17.MyClass</element>. -因此错误是有道理的.

I get an error when I do that though (Non white space characters cannot be added to content.) If I wrap the class in the element I see that the content written is <element>ConsoleApplication17.MyClass</element> - so the error makes sense.

有扩展方法可以自动反序列化,但这不是我想要的(这是客户端,但是我仍然希望有更好的东西).

I do have extension methods to de/serialize automatically, but that's not what I am looking for (this is client-side, but I would still like something more optimal).

有什么想法吗?

推荐答案

类似于这个?

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

这篇关于直接对XML Linq进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆