C# XML Insert comment into XML after xml tag

情到浓时终转凉″ 提交于 2019-11-30 23:14:45

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.

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();
}

I believe you can implement IXMLSeriablizable on your objects. If I remember correctly, ReadXML(XmlReader reader) and WriteXML(XmlWriter writer) from that interface are called automatically when serializing/de-serializing (CreateSchema, or whatever the third method is, doesn't need to be implemented).

The caveat of implementing it is that you now may need to implement it on all related nested objects. (i.e if you have a Department object that contains User objects and you want the comment on Departments, you will need to implement IXmlSeriablizable on both Department and User). Also, since you are managing the serialization directly, if you add a new property to a class, you will manually need to modify the IXmlSerializable methods.

I typically implement IXmlSerializable on my objects, as I like having direct control over what gets serialized and how.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!