简体   繁体   中英

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

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

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:

<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.

Try using [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.:

<?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>

XmlTextAttribute probably?

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM