使用属性和类的单个值将C#类序列化为XML

我正在使用C#和XmlSerializer来序列化以下类:

public class Title { [XmlAttribute("id")] public int Id { get; set; } public string Value { get; set; } } 

我希望这能序列化为以下XML格式:

 Some Title Value 

换句话说,我希望Value属性是XML文件中Title元素的值。 如果不实现我自己的XML序列化程序,我似乎无法找到任何方法,我想避免这种情况。 任何帮助,将不胜感激。

尝试使用[XmlText]

 public class Title { [XmlAttribute("id")] public int Id { get; set; } [XmlText] public string Value { get; set; } } 

这是我得到的(但我没有花很多时间调整XmlWriter,所以你在命名空间等方面得到了一堆噪音:

  Grand Poobah 

XmlTextAttribute可能吗?

 using System; using System.IO; using System.Text; using System.Xml.Serialization; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var title = new Title() { Id = 3, Value = "something" }; var serializer = new XmlSerializer(typeof(Title)); var stream = new MemoryStream(); serializer.Serialize(stream, title); stream.Flush(); Console.Write(new string(Encoding.UTF8.GetChars(stream.GetBuffer()))); Console.ReadLine(); } } public class Title { [XmlAttribute("id")] public int Id { get; set; } [XmlText] public string Value { get; set; } } }