public static void WriteXmlComments(string xmlSongFile, IEnumerable<XComment> commentNodes = null, bool saveOldVers = true, bool writeNewVers = true, string customComment = "")
{
const string CST_MAGIC = " CST v";
var sameComment = false;
var sameVersion = false;
var xml = XDocument.Load(xmlSongFile);
var rootnode = xml.Element("song");
if (rootnode == null)
throw new InvalidDataException(xmlSongFile + Environment.NewLine +
"XML file does not contain 'Song' node.");
// remove all xml comments
xml.DescendantNodes().OfType<XComment>().Remove();
if (commentNodes == null)
commentNodes = ReadXmlComments(xmlSongFile);
if (commentNodes != null)
{
// add back all non-magic (DDC, EOF, custom) comments first
foreach (var commentNode in commentNodes.Reverse())
{
if (!commentNode.ToString().Contains(CST_MAGIC))
rootnode.AddFirst(new XComment(commentNode));
if (!String.IsNullOrEmpty(customComment) && commentNode.ToString().Contains(customComment))
sameComment = true;
}
// add back old version info
foreach (var commentNode in commentNodes.Reverse())
{
if (commentNode.ToString().Contains(CST_MAGIC))
{
if (!commentNode.ToString().Contains(ToolkitVersion.version))
{
if (saveOldVers)
rootnode.AddFirst(new XComment(commentNode));
}
else
sameVersion = true;
}
}
if (!sameComment && !String.IsNullOrEmpty(customComment))
rootnode.AddFirst(new XComment(" " + customComment + " "));
// always put current CST version info first
if (sameVersion || writeNewVers)
rootnode.AddFirst(new XComment(CST_MAGIC + ToolkitVersion.version + " "));
}
xml.Save(xmlSongFile);
}