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

前端 未结 2 1012
无人共我
无人共我 2020-12-05 17:30

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

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

    public         


        
相关标签:
2条回答
  • 2020-12-05 18:07

    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; }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-05 18:09

    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>
    
    0 讨论(0)
提交回复
热议问题