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

时间:2012-02-29 17:53:22

标签: c# xml serialization

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

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序列化程序,我似乎无法找到任何方法,我希望避免这种情况。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:51)

尝试使用[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>

答案 1 :(得分:8)

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

}
相关问题