直接/从XML Linq序列化

有没有办法取消/序列化一个对象而不绕过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 – 所以错误说得通。

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

有任何想法吗?

像这样的东西?

  public XDocument Serialize(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(c); Console.WriteLine(doc.ToString()); }