2012-02-29 36 views
19

我使用C#和XmlSerializer的序列化以下类:序列化一个C#类为XML的属性和一个值类

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

    public string Value { get; set; } 
} 

我想这个序列化下列XML格式:

<Title id="123">Some Title Value</Title> 

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

回答

37

尝试使用[XmlText]

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

    [XmlText] 
    public string Value { get; set; } 
} 

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

<?xml version="1.0" encoding="utf-16"?> 
<Title xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     id="123" 
     >Grand Poobah</Title> 
+0

我知道必须有一些简单的东西,我失踪了,像一个魅力工作,谢谢。 – 2012-02-29 18:03:42

5

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

} 
相关问题