C# De/Serialize 直接 To/From XML Linq
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/314062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
De/Serialize directly To/From XML Linq
提问by Jonathan C Dickinson
Is there any way to de/serialize an object without round-tripping a XmlDocument/temp string? I am looking for something like the following:
有没有办法在不往返 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; }
}
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.
但是,当我这样做时出现错误(不能将非空白字符添加到内容中。)如果我将类包装在元素中,我会看到写入的内容是 <element>ConsoleApplication17.MyClass</element> - 所以错误说得通。
I dohave 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).
我确实有自动反/序列化的扩展方法,但这不是我想要的(这是客户端,但我仍然想要更优化的东西)。
Any ideas?
有任何想法吗?
采纳答案by Amy B
Something like 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());
}