2010-01-24 23 views
8

Quiero agregar en la parte superior de mi archivo xml algunas notas para el usuario que lo lee. Aunque no estoy seguro de cómo hacer esto con la serialización xml.¿Cómo insertar comentarios XML en Serialización XML?

yo estaba buscando en este post

C# XML Insert comment into XML after xml tag

XDocument document = new XDocument(); 
document.Add(new XComment("Product XY Version 1.0.0.0")); 
using (var writer = document.CreateWriter()) 
{ 
    serializer.WriteObject(writer, graph); 
} 
document.Save(Console.Out); 

pero no estoy realmente seguro de lo que está pasando y cómo añadir esto a mi código. Básicamente, solo tengo algunas clases que serializo en xml y las pego en una secuencia de memoria.

Así que no estoy seguro en qué punto debo agregar los comentarios.

Gracias

Código

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Serialization; 

namespace ConsoleApplication1 
{ 
    [XmlRoot("Course")] 
    public class MyWrapper 
    { 
     public MyWrapper() 
     { 
      TaskList = new List<Tasks>(); 
     } 

     [XmlElement("courseName")] 
     public string CourseName { get; set; } 

     [XmlElement("backgroundColor")] 
     public string BackgroundColor { get; set; } 

     [XmlElement("fontColor")] 
     public string FontColor { get; set; } 

     [XmlElement("sharingKey")] 
     public Guid SharingKey { get; set; } 

     [XmlElement("task")] 
     public List<Tasks> TaskList { get; set; } 

    } 

public class Tasks 
{ 
    [XmlAttribute("type")] 
    public string Type { get; set; } 

    [XmlElement("taskName")] 
    public string TaskName { get; set; } 

    [XmlElement("description")] 
    public string Description { get; set; } 

    [XmlElement("taskDueDate")] 
    public DateTime TaskDueDate { get; set; } 

    [XmlElement("weight")] 
    public decimal? Weight { get; set; } 

    [XmlElement("beforeDueDateNotification")] 
    public int BeforeDueDateNotification { get; set; } 

    [XmlElement("outOf")] 
    public decimal? OutOf { get; set; } 

} 

}

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Serialization; 
using System.IO; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      MyWrapper wrap = new MyWrapper(); 
      wrap.CourseName = "Comp 1510"; 
      wrap.FontColor = "#ffffff"; 
      wrap.BackgroundColor = "#ffffff"; 
      wrap.SharingKey = Guid.NewGuid(); 

      Tasks task = new Tasks() 
      { 
       TaskName = "First Task", 
       Type = "Assignment", 
       TaskDueDate = DateTime.Now, 
       Description = "description", 
       BeforeDueDateNotification = 30, 
       OutOf = 50.4M 
      }; 

      wrap.TaskList.Add(task); 
      var stream = SerializeToXML(wrap); 


     } 

     static public MemoryStream SerializeToXML(MyWrapper list) 
     { 

      XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper)); 
      MemoryStream stream = new MemoryStream(); 
      serializer.Serialize(stream, course); 
      return stream; 


     } 

    } 
} 
+0

Muéstrenos su código :-) – dtb

+0

(He agregado una solución alternativa a la respuesta vinculada en la pregunta.) – dtb

+0

Ok, agregué mi código. Para que pueda ver lo que estoy haciendo y posiblemente donde debería agregar ese código. – chobo2

Respuesta

17

Sólo hay que poner un XmlWriter como un nivel intermedio entre el MemoryStream y XmlSerializer:

static public MemoryStream SerializeToXML(MyWrapper list) 
{ 
    XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper)); 
    MemoryStream stream = new MemoryStream(); 
    XmlWriter writer = XmlWriter.Create(stream); 
    writer.WriteStartDocument(); 
    writer.WriteComment("Product XY Version 1.0.0.0"); 
    serializer.Serialize(writer, course); 
    writer.WriteEndDocument(); 
    writer.Flush(); 
    return stream; 
} 

Puede agregar cualquier XML antes y después del gráfico de objetos serializados (siempre que el resultado sea XML válido).

+5

El documento no se sancionará/formateará de forma predeterminada. Por lo tanto, debe configurarlo en el constructor: XmlWriter.Create (stream, new XmlWriterSettings {Indent = true}); O use un XmlTextWriter: XmlTextWriter writer = XmlTextWriter.Create (stream); writer.Formatting = Formatting.Indented; – row1

Cuestiones relacionadas