Search code examples
c#xmlxmlserializer

XmlSerializer to convert to XmlElement or string


I am storing developer notes in XML files within the project, to eliminate storing them on a SQL instance to reduce database calls.

I have my class set up to be Serialized

[Serializable]
public class NoteDto 
{
    [NonSerialized]
    private string _project;

    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    public string Project
    {
        get => _project;
        set => _project = value;
    }       
}

to create this element

<Note>
  <Date></Date>
  <Time></Time>
  <NoteText></NoteText>
  <Author></Author>
</Note>

The reason I do not want Project property serialized, is that the Note Element is in a parent element (NotesFor).

<NotesFor id="project value here">
  // note element here
</NotesFor>

I need the Project string to search for the Node where the NotesFor element id = Project then append the created element to the end of its children.

So that leaves two questions

  1. Do I create an XElement and append to current node or do I create a string to append to the node in the Xml file? I don't work much with Xml so I am not sure what the standard protocol is to update Xml files.
  2. Is there a better way to accomplish what I am trying to do?

Solution

  • You don't need to mark the class serializable.

    public class NoteDto 
    {
        public string Date { get; set; }
        public string Time { get; set; }
        public string Author { get; set; }
        public string NoteText { get; set; }
        [XmlIgnore]
        public string Project { get; set; }
    }
    

    You can serialize this with the following code, which I've implemented as an extension method:

    public static string ToXml<T>(this T thing)
    {
        if (thing == null)
            return null;
    
        var builder = new StringBuilder();
    
        new XmlSerializer(typeof(T)).Serialize(new StringWriter(builder), thing);
    
        return builder.ToString();
    }
    

    Which gets used like this:

    var note = new NoteDto
    {
        Date = "1/1/2018",
        Time = "4:00 PM",
        Author = "Some Guy",
        NoteText = "My Note",
        Project = "A Project"
    };
    var xml = note.ToXml();