Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将C#类序列化为具有属性和该类的单个值的XML_C#_Xml_Serialization - Fatal编程技术网

将C#类序列化为具有属性和该类的单个值的XML

将C#类序列化为具有属性和该类的单个值的XML,c#,xml,serialization,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文件中

我正在使用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序列化程序,我似乎找不到任何方法来实现这一点,我希望避免这种情况。任何帮助都将不胜感激。

可能吗

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

}

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

普巴大酒店

我知道一定有一些简单的东西我错过了。很有魅力,谢谢。