How do I use XmlSerializer to insert an xml string

前端 未结 4 1359
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 15:15

I have defined the following class:

public class Root
{
    public string Name;
    public string XmlString;
}

and created an object:

4条回答
  •  没有蜡笔的小新
    2020-12-10 15:20

    You can (ab)use the IXmlSerializable interface an XmlWriter.WriteRaw for that. But as garethm pointed out you then pretty much have to write your own serialization code.

    using System;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    
    namespace ConsoleApplicationCSharp
    {
      public class Root : IXmlSerializable
      {
        public string Name;
        public string XmlString;
    
        public Root() { }
    
        public void WriteXml(System.Xml.XmlWriter writer)
        {
          writer.WriteElementString("Name", Name);
          writer.WriteStartElement("XmlString");
          writer.WriteRaw(XmlString);
          writer.WriteFullEndElement();
        }
    
        public void ReadXml(System.Xml.XmlReader reader) { /* ... */ }
        public XmlSchema GetSchema() { return (null); }
        public static void Main(string[] args)
        {
          Root t = new Root
          {
            Name = "Test",
            XmlString = "bar"
          };
          System.Xml.Serialization.XmlSerializer x = new XmlSerializer(typeof(Root));
          x.Serialize(Console.Out, t);
          return;
        }
      }
    }
    

    prints

    
    
      Test
      bar
    
    

提交回复
热议问题