Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XML Insert comment into XML after xml tag

I am using a C# object to Serialize/Deserialize XML.

I would like to add a comment to the XML file whilst serializing, this comment will be a basic <!-- comment --> after the standard xml tag <?xml version="1.0" encoding="UTF-8"?>

This comment does not need to be deserialized, its a basic comment to indicate the product and version that created the xml file.

like image 647
Mark Redman Avatar asked Jul 02 '26 04:07

Mark Redman


2 Answers

You can serialize directly into a new XDocument using CreateWriter:

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

Alternatively, you can serialize into any other XmlWriter as well:

using (XmlWriter writer = XmlWriter.Create(Console.Out))
{
    writer.WriteStartDocument();
    writer.WriteComment("Product XY Version 1.0.0.0");
    serializer.WriteObject(writer, graph);
    writer.WriteEndDocument();
}
like image 61
dtb Avatar answered Jul 03 '26 19:07

dtb


Serialize it to XML, load that XML as an XDocument (or whatever API you want), insert the comment, save it out again. Simple, and should work with whatever API you want to use. You can do it all in memory using a MemoryStream as the temporary storage.

There may be a way of serializing directly into a new XDocument/XmlDocument, but I'm not aware of it.

like image 37
Jon Skeet Avatar answered Jul 03 '26 18:07

Jon Skeet