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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9504150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:39:52  来源:igfitidea点击:

Serialize a C# class to XML with attributes and a single value for the class

c#xmlserialization

提问by J Kerchner

I am using C# and XmlSerializer to serialize the following class:

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

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

    public string Value { get; set; }
}

I would like this to serialize to the following XML format:

我希望将其序列化为以下 XML 格式:

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

In other words, I would like the Value property to be the value of the Title element in the XML file. I can't seem to find any way to do this without implementing my own XML serializer, which I would like to avoid. Any help would be appreciated.

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

采纳答案by Nicholas Carey

Try using [XmlText]:

尝试使用[XmlText]

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

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

Here's what I get (but I didn't spend a lot of time tweaking the XmlWriter, so you get a bunch of noise in the way of namespaces, etc.:

这是我得到的(但我没有花很多时间调整 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>

回答by Konrad Morawski

XmlTextAttributeprobably?

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

}